[英]jQuery set button element active and disabled dynamically
我目前正在使用jQuery开发客户端脚本。
当我在1个输入字段中输入或删除文本时,我实现了将按钮元素设置为禁用或启用的功能。
但是,我需要检查2个输入字段是否具有值,否则应禁用按钮。 不过,如果我在1个输入字段中输入文字,则按钮始终处于启用状态...
HTML
<button type="button" id="btnSave">Save</button>
<button type="button" id="btnSubmit">Save</button>
<input type="text" id="BusinessLineIdList" />
<input type="text" id="Label" />
JS
$("#BusinessLineIdList").on("keyup", function () {
checkBusinessLine();
checkLabel();
});
$("#Label").on("keyup", function () {
checkLabel();
checkBusinessLine();
});
function checkLabel() {
if ($("#Label").val()) {
setBtnActive();
} else {
setBtnDisabled()
};
}
function checkBusinessLine() {
if ($("#BusinessLineId").val()) {
setBtnActive();
}
else {
setBtnDisabled();
}
}
function setBtnActive() {
$("#btnSave").removeAttr("disabled");
$("#btnSubmit").removeAttr("disabled");
};
function setBtnDisabled() {
$("#btnSave").attr('disabled', true);
$("#btnSubmit").attr('disabled', true);
};
您有解决该问题的想法吗? 谢谢
我会这样做。 在启用/禁用按钮之前,我们必须检查两个文本框的值。 这是一个工作的小提琴https://jsfiddle.net/71up0zfm/
我改变的jQuery代码:
$("#BusinessLineIdList").on("keyup", function () {
var x=checkBusinessLine();
var y=checkLabel();
if(x&&y)
setBtnActive();
else
setBtnDisabled();
});
$("#Label").on("keyup", function () {
var x=checkLabel();
var y=checkBusinessLine();
if(x&&y)
setBtnActive();
else
setBtnDisabled();
});
function checkLabel() {
var state=false;
if ($("#Label").val()) {
state=true;
}
return state;
}
function checkBusinessLine() {
var state=false;
if ($("#BusinessLineIdList").val()) {
state=true;
}
return state;
}
每次更改时,请同时检查它们并根据结果进行操作:
$("#BusinessLineIdList").on("keyup", callback);
$("#Label").on("keyup", callback);
function callback() {
if (isLabelHasValue() && isBusinessLineHasValue()) {
setBtnActive();
} else {
setBtnDisabled();
}
}
function isLabelHasValue() {
return $("#Label").val() && $("#Label").val().length > 0;
}
function isBusinessLineHasValue() {
return $("#BusinessLineId").val() && $("#BusinessLineId").val().length > 0;
}
function setBtnActive() {
$("#btnSave").removeAttr("disabled");
$("#btnSubmit").removeAttr("disabled");
};
function setBtnDisabled() {
$("#btnSave").attr('disabled', true);
$("#btnSubmit").attr('disabled', true);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.