Jquery 需要在下一个最近的类中显示错误消息,具体取决于输入

Jquery need to show error message in the next nearest class, depending on input

本文关键字:消息 错误 输入 取决于 显示 下一个 最近 Jquery      更新时间:2023-09-26

这是示例 http://jsfiddle.net/y53cd3qd/

具有多个输入表单。在每个输入表单旁边都有span class="numeric" .

<input type="text" id="miles_per_gallon" class="numeric" >
<span class="errmsg" style="color:red"></span>
<br/>
<input type="text" id="mileage" >
<span class="errmsg" style="color:red"></span>
<br/>

没有父div 或其他元素

要。如果用户键入不是数字,则在最近或最近的 nex class="errmsg"中显示错误

$(".numeric").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//$(".errmsg").html("Digits Only").show().fadeOut("slow");
$(this).siblings(".errmsg").html("hmm");
//alert("Digits only");
return false;
}
});

但是在所有class="errmsg"中显示错误消息。如何只在下一个最接近的地方显示?

使用这个:

$(this).next(".errmsg").html("hmm");

$(".numeric").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");
$(this).next(".errmsg").html("hmm");
//alert("Digits only");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="span_left">Miles per gallon<span class="required">*</span>: </span>
<input style="width:145px;" type="text" name="miles_per_gallon" id="miles_per_gallon" class="numeric" placeholder="Miles per gallon" value="" >
<span class="errmsg" style="color:red"></span>
<br/>
<span class="span_left">Mileage<span class="required">*</span>: </span>
<input style="width:145px;" type="text" name="mileage" id="mileage" value="" placeholder="Mileage" ><span class="errmsg" style="color:red"></span>
<br/>

我只是更改如下,

$(this).siblings(".errmsg").html("hmm"); 
to 
$(this).next(".errmsg").html("hmm");

看看这个。