Tips on preventing empty values in a textbox

    $(document).on("click", "label.radeem-textbox", function () {
        var content = $(".mytxt").text();
        $(".radeem-textbox").replaceWith("<input class='radeem-textbox redeem-textbox'/>");
        $(".radeem-textbox").val(content);
return false;
    });

    $(document).on("blur", "input.radeem-textbox", function () {
        var content = $(this).val();
        $(this).replaceWith("<label class='radeem-textbox'></label>");
        $(".radeem-textbox").text(content);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<a href="javascript:void(0)" class="right-side-margin-top right-side-margin-bottom display-block add-to-wishlist">

 <label  class="add-to-wish radeem-textbox">Redeem a Coupon</label>
                        </a>

I have jQuery code that allows labels to be converted into textboxes upon clicking. However, if nothing is entered in the textbox, both the textbox and label are not displayed. Is there a way to automatically focus on the textbox if nothing is entered?

<label  class="add-to-wish radeem-textbox">Redeem a Coupon</label>



<script type="text/javascript">
$(document).on("click", "label.radeem-textbox", function () {
    var content = $(".mytxt").text();       
    $(".radeem-textbox").replaceWith("<input class='radeem-textbox'/>");        
    $(".radeem-textbox").val(content);
    return false;       
});

$(document).on("blur", "input.radeem-textbox", function () {
    var content = $(this).val();
    $(this).replaceWith("<label class='radeem-textbox'></label>");      
    $(".radeem-textbox").text(content);
});

Answer №1

Ensure validation by using if(txt.trim()). You can learn more about the trim() function to check if the input box is empty or not. It only allows inputs that are not empty or null.

$(document).on("click", "label.radeem-textbox", function () {
    var txt = $(".mytxt").text();       
    $(".radeem-textbox").replaceWith("<input class='radeem-textbox'/>");        
    $(".radeem-textbox").val(txt);
    return false;       
});

$(document).on("blur", "input.radeem-textbox", function () {
    var txt = $(this).val();
  if(txt.trim()){
    $(this).replaceWith("<label class='radeem-textbox'></label>");      
    $(".radeem-textbox").text(txt);
    }
  else{
    console.log('enter text please')

    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label  class="add-to-wish radeem-textbox">Redeem a Coupon</label>

Another method: Use label tag for updating You can also try using the contenteditable attribute, which serves a similar purpose.

<label contenteditable="true">Click me to edit me</label>

Answer №2

$(document).on("focusout", "input.redemption-input", function() {
    var text = $(this).val();
    if($.trim(text).length) { // check if not empty
        $(this).replaceWith("<label class='redemption-label'></label>");
        $(".redemption-label").text(text);
    } else {
        // value is empty, so focus back on input
        $(this).focus();
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for using jQuery to alter webpage elements

Having an issue here. Attempting to modify a webpage using jquery and could benefit from some guidance with an illustration: On my current webpage, I am looking to extract information from a different site. It's comparable to... imagine creating a pl ...

Discovering a specific number within an ID and selecting the corresponding checkbox using jQuery

Let me explain a bit about my situation. I have two sets of checkboxes set up differently: <input type="checkbox" id="quick" value="6" /> <input type="checkbox" id="quick" value="3" /> The second set looks like this: <div class="check1"&g ...

How to Disable Checkbox in Ionic Framework's Ion-List

Feel free to check out my Codepen project. Within this demonstration, I am working with two list arrays - one called items and the other items1. My goals are: To display a list where certain items from the items array are already checked based on the c ...

Implementing a line break within a JavaScript function specifically designed for formatting images

As I am not a javascript developer, the code I have been given for debugging is somewhat challenging. The issue at hand involves an iOS module where a .js CSS file has been set up and images are loading improperly, resulting in the need for horizontal scro ...

Using jQuery AJAX for JavaScript redirection

I have been working on a JQuery AJAX response, and need help redirecting to another view. Here is the code snippet: $.ajax({ url: "/Home/PersistSelections", type: 'post', contentType: "application/json; ...

Is there an easy way to determine if an element inside a Vue component is overflowing?

I created a unique component called ResultPill which includes a tooltip feature (implemented using vuikit). The text displayed in the tooltip is determined by a getter function called tooltip, utilizing vue-property-decorator. Here are the relevant parts o ...

Using Ajax to invoke a C# webmethod

I'm trying to call a webmethod defined in this specific class <%@ WebService Language="C#" Class="emt7anReyady.myService" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Linq; usi ...

Limit the bootstrap datepicker to display only certain dates and today's date

I've integrated the Bootstrap Datepicker into my website. I need to customize it so that only specific dates are enabled, including today's date, and all other years, months, and days are hidden from the Datepicker. How can I achieve this? Furth ...

Menu button is expanded without the need to click

The Bootstrap 5 button extends the default behavior and does not collapse. Here is the code: <nav id="header-nav" class="navbar navbar-expand-lg navbar-light"> <div class="container"> <a class= ...

Utilizing IISNode and/or nodemon for efficient node.js development on Windows platform

For my node.js application running on Windows, I currently utilize IISNode both locally during development and on production hosting. Would incorporating nodemon (or a comparable module that monitors file changes and restarts node.exe when necessary) pro ...

What is the best way to utilize this resulting value as an input?

I am trying to generate a random number using math.random and use that value in the following script: let bday = Math.floor( Math.random() * (30 - 1 + 1) + 1 ); await test.page.select('select[name="day_select"]',bday); However, I am ...

When employing jQuery AJAX with the text() method, why does any HTML contained in the XML fail to display?

My Jquery Ajax is functioning well, but I am facing an issue with styling text in my XML file. When trying to bold or italicize a word within the XML using HTML tags, it does not render properly. I suspect this might be due to using the .text() function. C ...

Make sure to enable contentEditable so that a <br> tag is inserted

When using a contentEditable, it automatically wraps words to create a new line once the width of the editable area is reached. While this feature is useful, I am facing an issue when parsing the content afterwards as I need it to insert a <br> tag ...

jquery token selection dropdown box

I am not encountering any errors with this particular issue, however upon reviewing the plugin it appears that it should only toggle "admin admin" in the dropdown list. I am currently utilizing the most recent version of jquery. Upon further investigation ...

How to extract a variable from a mongoose find method in a Node.js application

Within my Node.js program, I utilize my Mongoose database to query for a specific value in a collection, of which there is only one value present. var myValueX; myCollection.find(function(err, post) { if (err) { console.log('Error ...

What are effective ways to prevent anythingSlider (jQuery plugin) from sliding?

How can I prevent the slider from sliding backwards on anythingslider when the current page is 1? I do not want it to rotate. I have tried: onSlideBegin : function(e, slider){ return false; } // there is no check I just need to know how to stop slidin ...

What is the best way to retrieve data based on a condition using JavaScript within a React application?

I am struggling to load only a specific number of rows that meet a certain condition. Unfortunately, the current code is fetching all 25 rows and the condition is not being applied correctly. If anyone could provide assistance, it would be greatly apprec ...

Managing a fixed footer in an Android webview to prevent it from obstructing an input field when the soft keyboard appears

I am working with a webview that contains a React app, not React Native. The webview features a login page with two input fields and a fixed footer. However, when one of the input fields is focused, the footer moves up and covers part of the input field, ...

Enhancing drag items in jquery UI Sortable with customizable drag images

Is there a method to include a drag image on the item being dragged? I attempted to achieve this using the code below: $('.selector').sortable({ start: function( event, ui ) { $(ui.item).addClass('dragImage'); } }); While t ...

Is there a way to display "Loading" text upon clicking a button using angular.js?

Check out this unique progress bar code snippet: <svg class="center-block progress-bar-round" width="200" height="200"> <circle cx="100" cy="100" r="90" fill="none" stroke=& ...