所以我现在正在处理一个网络表单,我需要在输入具有特定值后禁用所有形式的输入。一旦下拉列表达到该值,是否有一种简单的方法来处理? 目前我正在这样做:
setInterval('check()', 5000);
function check() {
// Disable all fields if the answer was no.
if ($("#has_contract").val() == 0) {
disable();
}
function disable() {
$("#inputs *").prop('disabled', true);
alert("There is no contract, please get a contract.");
}
has_contract 是我的元素,如果#has_contract 的值为 0,#inputs 包含我想禁用的所有输入。**
但这并不理想。 有没有更好的方法来执行此操作,而不是每隔 X 秒就不断检查一次?
最佳答案
您可以在更改时检查值,而不是每 5 秒检查一次值。
// collect elements
var $hasContract = $("#has_contract");
var $inputs = $("#inputs input");
// on change, check the input
$hasContract.on('change', checkForm);
// Checks the hasContract input for a value
// of 0. If it does, disable the form.
function checkForm() {
if($hasContract.val() == 0) {
$inputs.attr('disabled', true);
}
}
此外,当您使用 setTimeout 或 setInterval 时,您不必使用字符串。 Javascript 支持将函数作为变量传递。见下文。
// Do NOT do this
setInterval('check()', 5000);
// Do this instead
setInterval(check, 5000);
// or this
setInterval(function() {
//preform the check...
}, 5000);
关于javascript - 在下拉列表更改时禁用输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17354590/