简体   繁体   English

如何动态启用/禁用按钮

[英]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此为你工作类型的事件。

Demo: http://jsfiddle.net/7nywe/ 演示: http//jsfiddle.net/7nywe/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM