[英]Disable submit-button in validation with jquery
我正在尝试使用jQuery验证表单,而我现在要执行的操作是禁用提交按钮,直到正确填写所有字段。 这是我的方法: http : //jsfiddle.net/w57hq430/
<input type="text" name="commodity">Commodity
<input type="text" name="plz">PLz
<input type="submit">
和实际的jQuery:
$(document).ready(function() {
var error = null;
$('input[name=commodity]').focusout(function() {
var com = $('input[name=commodity]').val();
if($.isNumeric(com)) {
error ="asd";
}
else {
alert("commodity has to be numeric");
}
});
$('input[name=plz]').focusout(function() {
var com = $('input[name=plz]').val();
if($.isNumeric(com)) {
error ="asd";
}
else {
alert("plz has to be numeric");
}
});
if(error != null) {
$('input[type=submit]').attr('disabled', 'disabled');
}
else {
$('input[type=submit]').removeAttr('disabled');
}
});
我知道这段代码会阻止所有字段正确时单击提交按钮,因为这是我是否正确使用mouseout的测试。但是,这不起作用。即使输入了一些数字,变量错误也为null进入文本字段(应将其设置为“ asd”)。其余的代码是否无法访问我的变量?还是其他错误?
即使输入文本后错误为null的原因是,您只运行了一次此功能,即文档加载完成时。
相反,您将需要在字段的文本更改时验证字段,并以这种方式处理提交按钮上的Disabled标志。
另外,您不希望两个if
语句中的error字段都位于var
infront前面。
我会尝试一下,将验证移到一个函数中(而不是共享一个错误变量,否则您不知道何时将其清空),并在完成其中一个字段的编辑时触发。
您可以在此JSFiddle中尝试
$(document).ready(function() {
var toggleButton = function() {
// Check validity of 1st input
if($.isNumeric($('input[name=commodity]').val()) === false) {
$('input[type=submit]').attr('disabled', 'disabled');
error = "commodity has to be numeric";
// Check validity of 2nd input
} else if ($.isNumeric($('input[name=plz]').val()) === false) {
$('input[type=submit]').attr('disabled', 'disabled');
error = "plz has to be numeric";
} else {
$('input[type=submit]').removeAttr('disabled');
}
};
$('input[name=commodity]').focusout(function() {
toggleButton();
});
$('input[name=plz]').focusout(function() {
toggleButton();
});
// Disable submit button right at the start
toggleButton();
});
尝试使用,最好检查表单在提交点击时是否有效,而不是在字段的每次更改事件中都有效...
$(":submit").click(function(){
if(IsFormValid() == false)
return false;
});
function IsFormValid()
{
//Check form fields are valid
if form is valid
return true;
return false;
}
也许如果可以的话,我建议您使用一个jquery插件,它可以帮助您节省重新发明轮子的时间,也许这个 ,它可以使您禁用“提交”按钮
您的代码有一些问题,其中的一些问题在已发布的答案中被提及,而有些问题则没有,例如,当您有两个字段时,用这种方式一个错误var不够,而且您也不会在每次更改中都调用按钮状态函数。
尝试这个:
$(document).ready(function() {
$('input[type=submit]').attr('disabled', 'disabled');
var IsError1 = 0;
var IsError2 = 0;
$('input[name=commodity]').focusout(function() {
var com = $('input[name=commodity]').val();
if(!$.isNumeric(com)) {
alert("commodity has to be numeric");
IsError1 = 1;
}else {
IsError1 = 0;
}
setButtonState();
});
$('input[name=plz]').focusout(function() {
var com = $('input[name=plz]').val();
if(!$.isNumeric(com)) {
alert("plz has to be numeric");
IsError2 = 1;
}else {
IsError2 = 0;
}
setButtonState();
});
function setButtonState(){
if(IsError1 == 0 && IsError2 == 0) {
$('input[type=submit]').removeAttr('disabled');
} else {
$('input[type=submit]').attr('disabled', 'disabled');
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.