[英]How to dynamically enable/disable a button
Based on the answer here , I tried to create a similar validation function: 根据这里的答案,我试图创建一个类似的验证函数:
<html>
<head>
<script>
$("#my_name_id").on("change", function() {
if (!$("#my_name_id").val()) {
$("#button_id").attr("disabled", "disabled");
} else {
$("#button_id").attr("enabled", "enabled");
}
});
</script>
</head>
<body>
<form action="" name="test_form" id="test_form_id" method="post">
<input type="text" name="my_name" id="my_name_id" placeholder="Type your name"/>
<button type="submit" id="button_id">My button</button>
</form>
</body>
</html>
In this example, I would like to continually check to see if the input box contains any characters. 在此示例中,我想不断检查输入框是否包含任何字符。 If it does, then the button should be enabled (clickable).
如果是这样,则应该启用该按钮(可单击)。 If the input box does not contain any text, then the button should be disabled.
如果输入框不包含任何文本,则应禁用该按钮。
However, in my case the button always remains enabled. 但是,就我而言,该按钮始终保持启用状态。 What am I doing wrong here?
我在这里做错了什么?
No enabled
attribute in HTML for , so manipulate the disabled
attribute: HTML中没有为
enabled
属性,因此请操作disabled
属性:
<script>
$("#my_name_id").on("change", function () {
if (!$("#my_name_id").val()) {
$("#button_id").attr("disabled", "disabled");
} else {
$("#button_id").removeAttr("disabled");
}
}).trigger('change');;
</script>
You should use prop
, not attr
. 您应该使用
prop
而不是attr
。 After all your code will become simpler: 毕竟,您的代码将变得更加简单:
$("#my_name_id").on("change keyup", function() {
$("#button_id").prop("disabled", !this.value);
})
.trigger('change');
Also note how you can use trigger
in order to run initial check on page load automatically. 还要注意如何使用
trigger
来自动对页面加载进行初始检查。 I also included keyup
event for this to work as you type. 我还包括
keyup
此为你工作类型的事件。
You should use prop()
您应该使用
prop()
$("#button_id").prop("disabled", true); // disabled
$("#button_id").attr("disabled", false); // enabled
You should use prop
when you are dealing with boolean types. 在处理布尔类型时,应使用
prop
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.