Enable and disable textbox if checkbox is checked

别来无恙 提交于 2019-12-13 01:24:31

问题


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>

回答1:


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/




回答2:


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:


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>


来源:https://stackoverflow.com/questions/28760345/enable-and-disable-textbox-if-checkbox-is-checked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!