如果选中复选框,则启用和禁用文本框

时间:2015-02-27 08:16:58

标签: javascript html checkbox textbox

我按照类似问题的回答建议阅读此article。我做了文章所说的一切,但最终的结果并不是我想要的。

我希望默认情况下禁用该文本框。选中该复选框后,将启用文本框。

默认启用了文本框,当选中该复选框时,文本框被禁用。

这是我的代码:

<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>

3 个答案:

答案 0 :(得分:3)

您可以简化代码:

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

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

答案 1 :(得分:1)

复选框和输入元素是兄弟姐妹,因此您可以使用

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

答案 2 :(得分:1)

如果您使用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>