如何使用jQuery检查所有表单字段是否包含值
我需要知道所有字段是否都有值,如果有,我想激活提交按钮 我看过插件,但我不知道我需要/应该使用哪一个如何使用jQuery检查所有表单字段是否包含值,jquery,forms,submit,Jquery,Forms,Submit,我需要知道所有字段是否都有值,如果有,我想激活提交按钮 我看过插件,但我不知道我需要/应该使用哪一个 表单使用输入,文本框和下拉选择,您可以使用jquery通过控件id来选择所需的控件。我建议您不必支持插件,插件对您来说基本上是一个黑框 标记: <input type="text" id="myTextBox" /> <input type="text" id="x" /> <select id="y" /> 您可以根据有效的设置启用/禁用提交按钮。如果
表单使用
输入
,文本框
和下拉选择
,您可以使用jquery通过控件id来选择所需的控件。我建议您不必支持插件,插件对您来说基本上是一个黑框
标记:
<input type="text" id="myTextBox" />
<input type="text" id="x" />
<select id="y" />
您可以根据有效的设置启用/禁用提交按钮。如果您不想使用插件,可以执行类似的简单操作(注意:我还没有测试过): 然后在某些事件上(可能是
聚焦
或模糊
)调用此函数,并根据返回值切换提交按钮
var $submit = $('#a-form').find('input[type="submit"]'),
$inputs = $('#a-form').find('input, textarea').not('[type="submit"], [type="hidden"]');
$inputs.on('change', function () {
var error = false;
$.each($inputs, function (index, element) {
if ($(this).val() == '') {
error = true;
$(this).css({ backgroundColor : 'red' });
} else {
$(this).css({ backgroundColor : 'white' });
}
});
if (error) {
$submit.prop('disabled', true);
} else {
$submit.prop('disabled', false);
}
});
这会将事件处理程序绑定到change
事件的输入表单,该表单检查表单中每个输入的值,如果任何输入为空,则禁用提交按钮。它还将任何空白输入的背景色
更改为红色
这是一个演示:怎么样?val()
是falsy…$el.val()!=''代码>-->$el.val()
/**
* Checks to see if all of the values in a form are filled in.
*
* @param formId String the id of the form to check (without the #)
* @return boolean True indicates all form fields are filled in
*/
function checkForm(formId){
var isFormComplete = true;
$('#' + formId).find('input,select,textarea').each(function(){
var formValue = jQuery.trim($(this).val());
if(!formValue){
isFormComplete = false;
}
});
return isFormComplete;
}
var $submit = $('#a-form').find('input[type="submit"]'),
$inputs = $('#a-form').find('input, textarea').not('[type="submit"], [type="hidden"]');
$inputs.on('change', function () {
var error = false;
$.each($inputs, function (index, element) {
if ($(this).val() == '') {
error = true;
$(this).css({ backgroundColor : 'red' });
} else {
$(this).css({ backgroundColor : 'white' });
}
});
if (error) {
$submit.prop('disabled', true);
} else {
$submit.prop('disabled', false);
}
});