[英]Prevent submission when fields are blank and display error message
I have lots of different forms on my website. 我的网站上有很多不同的表格。 I want to use Jquery to: 我想使用Jquery来:
All the different forms link to the same Jquery script, so I have to make sure that my jquery doesn't make any references to a specific form (otherwise, I will have to write a different script for each form). 所有不同的表单都链接到相同的Jquery脚本,因此我必须确保jquery不会对特定表单进行任何引用(否则,我将不得不为每种表单编写不同的脚本)。
I thought the best way to do this would be to an each function to loop through the input fields to check if they are blank and then use event.preventDefault(); 我认为最好的方法是使每个函数循环输入字段以检查它们是否为空,然后使用event.preventDefault();。 to stop the form from submitting and addClass to highlight the fields. 阻止表单提交,并使用addClass突出显示字段。
The each function works but the preventdefault/addclass don't seem to work. 每个函数都起作用,但preventdefault / addclass似乎不起作用。 I'm not sure what I am doing wrong. 我不确定自己在做什么错。 Here is my code: ( JSFiddle version) 这是我的代码:( JSFiddle版本)
$(document).ready(function () {
$('.names').submit(function(){
$('.names input[type=text]').each(function(n,element){
if ($(element).val()=='') {
event.preventDefault();
alert('Some fields are blank (highlighted in red). Please fill them in');
($element).addClass("error");
return false;
}
});
return true;
});
});
How can I get it to work? 我如何使它工作? Also would it be possible to apply the error class to the parent <p>
tag of the input field rather than the field itself? 还可以将错误类应用于输入字段的父<p>
标记而不是字段本身吗?
event
is undefined. event
未定义。 Catch the parameter in your submit-callback and invoke preventDefault on that: 在您的Submit-callback中捕获参数,并在其上调用preventDefault:
$(document).ready(function () {
$('.names').submit(function (e) {
$(this).find('input[type=text]').each(function (n, element) {
if ($(element).val() == '') {
e.preventDefault();
alert('Some fields are blank (highlighted in red). Please fill them in');
$(element).parent().addClass("error");
return false;
}
});
return true;
});
});
Note that: 注意:
($element)
is also undefined, you meant $(element)
. ($element)
也是未定义的,您的意思是$(element)
。 $(element).parent()
. 要将错误类添加到父级,请使用$(element).parent()
。 $(this).find('input[...]')
instead of $('.names input[...]')
. 使用$(this).find('input[...]')
代替$('.names input[...]')
。 This way, you only validate the form that you are submitting. 这样,您只需验证您提交的表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.