user5005768 user5005768 - 1 month ago 12
jQuery Question

Jquery Input Field Validation: How to find the closest span by its class name on input keypress event

i want to show warning message on span of any input that only takes number.I am using class for span because i have many inputs that only takes number.

Here is html & css:

.errmsg {
color: red;
}

<div class="input-group" style="">
<input type="text" id='input_1' class="form-control number_only">
<span class="errmsg"></span>
</div>
<div class="input-group" style="">
<input type="text" id='input_2' class="form-control number_only">
<span class="errmsg"></span>
</div>
<div class="input-group" style="">
<input type="text" id='input_3' class="form-control number_only">
<span class="errmsg"></span>
</div>


Here is my JQuery Code:

$(document).ready(function () {
//called when key is pressed in input of class number_only
$(".number_only").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 != 46 && (e.which < 48 || e.which > 57)) {
//display error message
$(this).closest('.errmsg').html("Digits and single dot Only").show().fadeOut("slow");
return false;
}
});
});


the above code is not getting the closest span. please help.

Answer

Use with next() instead of closest(). its search next nearest element.

$(document).ready(function () {
      //called when key is pressed in input of class number_only
      $(".number_only").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 != 46 && (e.which < 48 || e.which > 57)) {
    			//display error message
    			$(this).next('.errmsg').html("Digits and single dot Only").show().fadeOut("slow");
    			return false;
    		 }
       });
    });
.errmsg {
      color: red;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-group" style="">
      <input type="text"  id='input_1' class="form-control number_only">
      <span class="errmsg"></span>	
    </div>
    <div class="input-group" style="">
      <input type="text"  id='input_2' class="form-control number_only">
      <span class="errmsg"></span>	
    </div>
    <div class="input-group" style="">
      <input type="text"  id='input_3' class="form-control number_only">
      <span class="errmsg"></span>	
    </div>

Comments