如果出现错误,请停止在jquery中提交表单

这是我的代码: http : //jsfiddle.net/Xk38X/6/

$('#register').click(function() { if( $('#company_f').val().length == 0 ) { $('#company_f').css("border", "solid 1px red"); } }); 

问题是即使错误仍然发送表格。 任何人都可以告诉我,如果用户点击按钮并且公司字段没有填写,我如何停止提交表单。

谢谢。

使用return false或event.preventdefault()

 $('#register').click(function (e) { if ($('#company_f').val().length == 0) { $('#company_f').css("border", "solid 1px red"); return false; // or e.preventdefault(); } }); 

一个更好的代码版本

 var company_f = $('#company_f'); //cache your selector $('#register').click(function (e) { if (company_f.val().length == 0) { company_f.css("border", "solid 1px red"); return false; // or e.preventdefault(); } }); 

另请阅读HTML必需属性

这是我的方式:

  $('#register').click(function(event) { if( $('#company_f').val().length == 0 ) { event.preventDefault(); $('#company_f').css("border", "solid 1px red"); } });