Search code examples
javascriptjqueryhtmltextboxonkeyup

Error message beside textbox onkeyup event


I have textboxes that I want to show the error prompt beside it onkeyup event, but with no luck, it doesn't work. I have this as my reference: I want to show error message beside my textbox rather than alert in onkeyup event

$(function() {
  $("#name").next('span').hide();
  $("#name").keyup(function() {
    var input = $(this).val();
    var span = $(this).next('span');

    if (name == "") {
      span.text("Please enter your name").show();
      return;
    }
    span.text('').hide();
  });

  $("#age").next('span').hide();
  $("#age").keyup(function() {
    var input = $(this).val();
    var span = $(this).next('span');

    if (age == "") {
      span.text("Please enter your age").show();
      return;
    }

    span.text('').hide();

  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="name" name="name" />
<hr>
<span></span>
<input type="text" id="age" name="age" />
<span></span>


Solution

  • You are using wrong variable names to check the values of the name field and age field.

    Also, the span for the name field is after the hr it should be right next to the input field.

    Check the snippet below, see the comments added;

    Notice the Regex .replace(/\s/g,'') for removing all whitespace in the if condition.

    $(function() {
      $("#name").next('span').hide();
      $("#name").keyup(function() {
        var input = $(this).val();
        var span = $(this).next('span');
    
        if (input.replace(/\s/g,'') == "") { // wrong variable, name is undefined, should be input, also the regex is for removing all whitespaces;
          span.text("Please enter your name").show();
          return;
        }
        span.text('').hide();
      });
    
      $("#age").next('span').hide();
      $("#age").keyup(function() {
        var input = $(this).val();
        var span = $(this).next('span');
    
        if (input.replace(/\s/g,'') == "") { // same here
          span.text("Please enter your age").show();
          return;
        }
    
        span.text('').hide();
    
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="text" id="name" name="name" />
    <span></span> <!-- span should be here, before the hr line break -->
    <hr>
    
    <input type="text" id="age" name="age" />
    <span></span>