在不加载login.php
的情况下提交时,如何使用jQuery检查文本字段是否为空
<form action="login.php" method="post">
<label>Login Name:</label>
<input type="text" name="email" id="log" />
<label>Password:</label>
<input type="password" name="password" id="pwd" />
<input type="submit" name="submit" value="Login" />
</form>
谢谢。
发布于 2013-05-15 12:46:01
您可以使用'required‘http://jsbin.com/atefuq/1/edit
<form action="login.php" method="post">
<label>Login Name:</label>
<input required type="text" name="email" id="log" />
<label>Password:</label>
<input required type="password" name="password" id="pwd" />
<input required type="submit" name="submit" value="Login" />
</form>
发布于 2013-05-15 12:48:01
一个简单的解决方案是这样的:
$( "form" ).on( "submit", function() {
var has_empty = false;
$(this).find( 'input[type!="hidden"]' ).each(function () {
if ( ! $(this).val() ) { has_empty = true; return false; }
});
if ( has_empty ) { return false; }
});
注意:jQuery.on()
方法只在jQuery版本的1.7+中可用,但它现在是附加事件处理程序的首选方法。
此代码遍历表单中的所有输入,如果其中任何输入没有值,则通过返回false来阻止表单提交。注意,它不会向用户显示任何类型的消息,说明表单提交失败的原因(我强烈建议添加一个)。
或者,您可以查看jQuery validate插件。它能做到这一点,还能做更多的事情。
注意:这种类型的技术应该始终与服务器端验证结合使用。
发布于 2013-05-15 12:49:34
您需要向表单submit事件添加一个处理程序。在处理程序中,您需要检查每个文本字段,如果这些值不为空,请选择元素和密码字段。
$('form').submit(function() {
var res = true;
// here I am checking for textFields, password fields, and any
// drop down you may have in the form
$("input[type='text'],select,input[type='password']",this).each(function() {
if($(this).val().trim() == "") {
res = false;
}
})
return res; // returning false will prevent the form from submitting.
});
https://stackoverflow.com/questions/16556968
复制相似问题