gpt4 book ai didi

javascript - Jquery 错误消息显示在每个字段上

转载 作者:行者123 更新时间:2023-11-28 05:46:55 25 4
gpt4 key购买 nike

我有一个 html 表单,在某些字段中只需要提交数字。如果输入文本,则会显示错误消息。它的工作没有达到标准。在三个字段中,如果有人输入任何文本,则会在所有三个字段中显示错误消息。

我想要的是 - 显示当前字段而不是所有字段的错误消息。

Jquery 代码是:

$(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;
}
});
});

HTML 代码是:

<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>

最佳答案

可以使用.prev()选择输入之前的错误消息范围

$(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>

关于javascript - Jquery 错误消息显示在每个字段上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38440604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com