user3410277 user3410277 - 4 months ago 9
HTML Question

Jquery error message showing on every fields

I have a html form and in some of the fields only digits to be submitted. If text is entered, it will show error message. It is working not up to the marks. Out of three fiels, if some body enters any text, its showing error message in all the three filed.

What I want is- the error message to be shown for the current field instead of all the filed.

The Jquery code is:

$(document).ready(function () {
//called when key is pressed in textbox
$(".quantity").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$(".errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});


The HTML CODE is:

<form method="post" name="data" action=" ">
Amount: <span class="errmsg"></span><br>
<input type="text" name="amount" class="quantity" /><br><br>
Interest: <span class="errmsg"></span><br>
<input type="text" name="interest" class="quantity" /><br><br>
Duration: <span class="errmsg"></span><br>
<input type="text" name="duration" class="quantity" /><br><br>
<input type="submit" name='submit' onclick="show_confirm()" value="SUBMIT">
</form>

Kld Kld
Answer

You can use .prev() to select the error message span before the input

$(document).ready(function () {
  //called when key is pressed in textbox
  $(".quantity").keypress(function (e) {
    var elem =$(this);
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        elem.prev().prev(".errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The HTML CODE is:

<form method="post" name="data" action="  ">
     Amount:  <span class="errmsg"></span><br>
     <input type="text" name="amount" class="quantity" /><br><br>
     Interest:  <span class="errmsg"></span><br>
     <input type="text" name="interest" class="quantity" /><br><br>
     Duration: <span class="errmsg"></span><br>
     <input type="text" name="duration" class="quantity" /><br><br>
     <input type="submit" name='submit'  onclick="show_confirm()" value="SUBMIT"> 
</form>

Comments