未选中复选框时如何禁用提交按钮? [英] How do i disable a submit button when checkbox is uncheck?

查看:15
本文介绍了未选中复选框时如何禁用提交按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有些东西似乎无法帮助我禁用提交按钮.有什么想法吗?

I have something here that cannot seem to help me disable the submit button. any ideas?

<input type="checkbox" checked="checked" id="checky"><a href="#">terms and conditions</a>
<input type="submit" id="postme" value="submit">

$('#checky').click(function(){
    if($(this).checked == false){
         $('#postme').attr("disabled","disabled");   
    } else {
        $('#postme').removeAttr('disabled');
    }
});

推荐答案

您应该检查属性 checked 而不是方法.

You should be checking for the attribute checked and not the method.

更新小提琴:http://jsfiddle.net/8YBu5/7/

$('#checky').click(function(){
    if($(this).attr('checked') == false){
         $('#postme').attr("disabled","disabled");   
    } else {
        $('#postme').removeAttr('disabled');
    }
});

编辑

记住,这段代码需要包裹在$(document).ready()里面或者放在你的html代码的底部,否则你的JS会自己绑定到没有经过的DOM元素上尚未加载并将失败.

Remember that this code needs to be wrapped inside $(document).ready() or put at the bottom of your html code, otherwise your JS will bind itself to DOM elements that have not been loaded yet and will fail.

将其包装在 .ready() 中

<script type='text/javascript'>
$(document).ready(function(){
    $('#checky').click(function(){
        if($(this).attr('checked') == false){
             $('#postme').attr("disabled","disabled");   
        } else {
            $('#postme').removeAttr('disabled');
        }
    });
});
</script>

此代码可以放在文档中的任何位置,并且只会在 DOM 准备就绪后触发,因此您不必担心过早触发.

This code can be put anywhere in the document and will only trigger once the DOM is ready so you don't have to worry about premature triggers.

将其放在文档底部

<!-- some HTML -->
<script type='text/javascript'>
        $('#checky').click(function(){
            if($(this).attr('checked') == false){
                 $('#postme').attr("disabled","disabled");   
            } else {
                $('#postme').removeAttr('disabled');
            }
        });
</script>
</body>
</html>

如果您将它放在文档的底部,则不需要将其包装在 .ready() 中,因为在加载其他所有内容之前不会读取 javascript.这个方法有性能提升(如果你有很多JS)

If you're putting it at the bottom of your document, you don't need to wrap it in .ready() because the javascript will not be read until everything else has loaded. There is a performance boost in this method (if you have a lot of JS)

您可以使用其中任何一种方法来确保您的 JS 仅在 完成加载后将事件处理方法绑定到 DOM 元素.

You can use either one of these methods to make sure that your JS binds event handling methods to DOM elements only after they have finished loading.

这篇关于未选中复选框时如何禁用提交按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆