Enable and disable textbox if checkbox is checked

2019-08-05 07:00发布

I read this article as suggested by an answer for a similar question. I did everything the article said, but the end result wasn't what I wanted.

I want the text box to be disabled by default. When the checkbox is checked, the textbox is enabled.

What happened was that the textbox is enabled by default, and when the checkbox is checked, the textbox is disabled.

Here is my code:

<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条回答
【Aperson】
2楼-- · 2019-08-05 07:27

The checkbox and the input elements are siblings so you can use

$(document).ready(function () {
    $('.input_control').prop('checked', true);
    $('.input_control').change(function () {
        $(this).siblings('input').prop('disabled', this.checked)
    });
});
查看更多
叛逆
3楼-- · 2019-08-05 07:30

If you use jQuery 1.6 or later, you can use this way. Of course, it works with the textarea element also. The demo below includes textarea element too.

edited: add textarea element.

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

查看更多
唯我独甜
4楼-- · 2019-08-05 07:34

You can simplify your code:

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

Demo: http://jsfiddle.net/t5qdvy9d/1/

查看更多
登录 后发表回答