提交前jQuery检查输入不为空

我一直在寻找关于如何做到这一点的不同线程,并将以下脚本放在一起,但是,即使我输入输入所以它们不是空的,我也会弹出警报,表单不会提交。

任何人都可以看到我做错了什么,或者有更简单/更有效的方法吗?

谢谢,

奥苏

HTML:

 

JS:

 // Validate form fields in Sign up form $(".signup-form").submit(function(){ var isFormValid = true; $(".signup-form .required input").each(function(){ if ($.trim($(this).val()).length == 0){ $(this).parent().addClass("highlight"); isFormValid = false; } else { $(this).parent().removeClass("highlight"); } }); if (!isFormValid) alert("Please fill in all the required fields (highlighted in red)"); return isFormValid; }); 

但是,感谢您的回答,我发现我收到错误消息的原因是因为提交按钮没有值,即值=“”,所以它也检查了输入。 为了纠正这个问题,我必须确保提交function只检查’文本’输入类型:

新JS:

 // Validate form fields in Sign up form $(".signup-form").submit(function(){ var isFormValid = true; $(".signup-form .required input:text").each(function(){ // Note the :text if ($.trim($(this).val()).length == 0){ $(this).parent().addClass("highlight"); isFormValid = false; } else { $(this).parent().removeClass("highlight"); } }); if (!isFormValid) alert("Please fill in all the required fields (highlighted in red)"); return isFormValid; }); 
  $('#signup').click(function(event) { event.preventDefault(); //validate and if it is valid serialize the form //else alert and return var isFormValid = true; $(".signup-form .required input").each(function(index, value){ if ($.trim($(value).val()).length == 0){ $(value).parent().addClass("highlight"); isFormValid = false; } else { $(value).parent().removeClass("highlight"); } }); if(isFormValid ){ $.post( 'validation.php', $('.signup-formt').serialize(), function( data ) { }); }else{ alert("Please fill in all the required fields (highlighted in red)"); } }); 
 $('input').each(function(index, obj){ if($(obj).val().length === 0) { $(obj).addClass('error'); } }); 

但我不记得是obj还是这个

.each多次运行脚本。 例如,如果您有3个空输入,则您使用的脚本会添加类.highlight 3次。 如果你想让你的页面保持清洁和干净,请将脚本放在下面。

 check = function() { var empty = $(".signup-form .required input").filter(function() { return this.value == ""; });//this checks if 1 or more inputs have no value if(empty.length) {//to be applied if at least 1 input has no value alert("Please fill in all the required fields (highlighted in red)"); $(".signup-form").addClass("highlight"); }else{ $(".signup-form").removeClass("highlight"); };} 

如果至少一个输入为空,这将警告消息ONCE。 然后只需将functiononclick添加到您的提交输入或您想要validation表单的任何按钮。