【发布时间】:2012-02-21 00:31:41
【问题描述】:
我需要知道是否所有字段都有值,如果有,我想激活提交按钮。
我看过插件,但不知道我需要/应该使用哪一个。
表单使用input、textbox和dropdown selects。
【问题讨论】:
-
Validate.JS 呢?
我需要知道是否所有字段都有值,如果有,我想激活提交按钮。
我看过插件,但不知道我需要/应该使用哪一个。
表单使用input、textbox和dropdown selects。
【问题讨论】:
如果你不想使用插件,你可以做这样简单的事情(注意:我还没有测试过):
/**
* 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;
}
然后在某些事件(可能是focus 或blur)上调用此函数,并根据返回值切换提交按钮。
【讨论】:
您可以使用 jquery 通过其 id 选择所需的控件。我建议不要支持插件——这对你来说本质上是一个黑盒子。
标记:
<input type="text" id="myTextBox" />
<input type="text" id="x" />
<select id="y" />
jquery:
var valid = $("#myTextBox").val() != "" &&
$("#x").val() != "" &&
$("#y").selectedIndex != 0; // if zero would be invalid for a select...
您可以根据有效启用/禁用提交按钮。
【讨论】:
val() 是假的...$el.val() != '' --> !$el.val()
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 事件的输入表单,该表单检查表单中每个输入的值,如果任何输入为空,则禁用提交按钮。它还将任何空白输入的background-color 更改为red。
这是一个演示:http://jsfiddle.net/2zjbM/1/
【讨论】: