启用如果复选框被选中禁用文本框(Enable and disable textbox if chec

2019-10-22 02:53发布

我看了这个文章通过一个类似的问题的答案的建议。 我所做的一切的文章说,但最终的结果不是我想要的。

我想在默认情况下禁用的文本框中。 当复选框被选中,文本框被启用。

当时的情况是,该文本框是默认启用的,当复选框被选中,文本框将被禁用。

这里是我的代码:

<td class="trow2">
    {$prefixselect}<input type="text" class="textbox" name="subject" size="40" maxlength="85" value="{$subject}" tabindex="1" />
    <input type="checkbox" class="input_control"  value="subject" />
    <strong>I believe {$forum['name']} is the best section for this topic.</strong>
</td>

<script type="text/javascript">
    $(document).ready(function(){
        $('.input_control').attr('checked', true);
        $('.input_control').click(function(){
            if($('input[name='+ $(this).attr('value')+']').attr('disabled') == false) {
                $('input[name='+ $(this).attr('value')+']').attr('disabled', true);
            }
            else {
                $('input[name='+ $(this).attr('value')+']').attr('disabled', false);    
            }
        });
    });
</script>

Answer 1:

您可以简化您的代码:

$(document).ready(function () {
    $('.input_control').change(function () {
        $('input[name=' + this.value + ']')[0].disabled = !this.checked;
    }).change();
});

演示: http://jsfiddle.net/t5qdvy9d/1/



Answer 2:

该复选框和输入元素是同级的,所以你可以使用

$(document).ready(function () {
    $('.input_control').prop('checked', true);
    $('.input_control').change(function () {
        $(this).siblings('input').prop('disabled', this.checked)
    });
});


Answer 3:

如果您使用jQuery 1.6或更高版本,可以使用这种方式。 当然,它的工作原理与textarea元素也。 下面的演示包括textarea元素太多。

编辑:添加textarea元素。

 $(document).ready(function(){ $('.input_control').change(function () { $(".textbox").prop('disabled', this.checked); $(".textarea").prop('disabled', this.checked); }); $('.input_control').prop('checked', true); $('.input_control').trigger('change'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> <input type="text" class="textbox" name="subject" size="40" maxlength="85" value="test subject" tabindex="1" /> <textarea class="textarea"></textarea> <p></p> <input type="checkbox" class="input_control" value="subject" /> <strong>I believe forum name is the best section for this topic.</strong> 



文章来源: Enable and disable textbox if checkbox is checked