簡體   English   中英

如果選中復選框,則啟用和禁用文本框

[英]Enable and disable textbox if checkbox is checked

我按照類似問題的答案建議閱讀了本文 我做了文章所說的一切,但最終結果不是我想要的。

我希望默認情況下禁用該文本框。 選中復選框后,將啟用文本框。

發生的事情是默認情況下該文本框處於啟用狀態,並且選中該復選框時,該文本框被禁用。

這是我的代碼:

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

您可以簡化代碼:

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

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

復選框和輸入元素是同級,因此您可以使用

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM