我在同一页面上使用了两次表单。
HTML 代码
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
使用一种表单可以正常工作,但是当我再次添加相同的表单时,它就停止工作了。第二个表单开始显示错误弹出警报,但即使我在表单字段中输入文本。
JS代码
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
如何使用相同的功能验证页面上的其他表单?
最佳答案
正如我所评论的,不能有多个具有相同 id
的元素。它违反了 HTML 规范,并且 jQuery id 选择器仅返回第一个(即使您有多个)。
就像您使用 jQuery 一样,我可能会建议另一种方法来实现您的目标。
首先,去掉codetext
id
。然后,不要使用 inline events (正如 MDN 文档中指出的那样,它们被认为是不好的做法),就像您所做的那样,您可以使用 .on()
使用 jQuery 指定事件处理程序。方法。
然后,在回调函数中,您可以使用 $(this)
引用表单本身,并使用方法 find()
定位名为 codetext
的子项。
而且,如果您调用e.preventDefault()
,您取消表单提交。
我的建议:
HTML 表单(可以根据需要重复):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
工作演示: https://jsfiddle.net/mrlew/8kb9rzvv/
关于javascript - 具有相同功能的多种表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42187394/