如何使用jQuery在提交时检查文本字段是否为空,而不加载。login.php
?
<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>
谢谢。
你可以使用jQuery绑定一个事件处理程序到 "submit "的JavaScript事件上。.submit
方法,然后被修剪 #log
文本字段的值,并检查是否为空的不喜欢。
$('form').submit(function () {
// Get the Login Name value and trim it
var name = $.trim($('#log').val());
// Check if empty of not
if (name === '') {
alert('Text-field is empty.');
return false;
}
});
您可以使用 "需要"。http:/jsbin.comatefuq1edit
<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>
一个简单的解决方案是这样的
$( "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验证 插件。它可以做到这一点,还有更多。
NB: 这种类型的技术应该始终与服务器端验证结合使用。
你需要在表单中添加一个处理程序 提交 事件中,你需要检查每个文本字段、选择元素和密码字段的值是否为空。在处理程序中,你需要检查每个文本字段、选择元素和密码字段的值是否为非空。
$('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.
});
我真的很讨厌那些不告诉我缺少了什么输入的表单,所以我改进了Dominic的答案--谢谢你。
在css文件中设置 "borderR "类为border为红色。
$('#<form_id>').submit(function () {
var allIsOk = true;
// Check if empty of not
$(this).find( 'input[type!="hidden"]' ).each(function () {
if ( ! $(this).val() ) {
$(this).addClass('borderR').focus();
allIsOk = false;
}
});
return allIsOk
});
你应该尝试用jquery validate插件。
$('form').validate({
rules:{
email:{
required:true,
email:true
}
},
messages:{
email:{
required:"Email is required",
email:"Please type a valid email"
}
}
})
function isEmpty(val) {
if(val.length ==0 || val.length ==null){
return 'emptyForm';
}else{
return 'not emptyForm';
}
}
$(document).ready(function(){enter code here
$( "form" ).submit(function( event ) {
$('input').each(function(){
var getInputVal = $(this).val();
if(isEmpty(getInputVal) =='emptyForm'){
alert(isEmpty(getInputVal));
}else{
alert(isEmpty(getInputVal));
}
});
event.preventDefault();
});
});
var save_val = $("form").serializeArray();
$(save_val).each(function( index, element ) {
alert(element.name);
alert(element.val);
});