[英]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.