【问题标题】:Enable and disable textbox if checkbox is checked如果选中复选框,则启用和禁用文本框
【发布时间】:2015-02-27 16:57:00
【问题描述】:

我按照类似问题的答案的建议阅读了此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>

【问题讨论】:

    标签: javascript html checkbox textbox


    【解决方案1】:

    您可以简化代码:

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

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

    【讨论】:

    • 谢谢!像魅力一样工作!
    • 有没有办法让它同时为
    • 我有同样的问题,但我使用单选按钮而不是复选框。我已经尝试了很多东西,但不明白为什么它不醒。
    【解决方案2】:

    复选框和输入元素是兄弟元素,所以你可以使用

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

    【讨论】:

      【解决方案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>

      【讨论】:

        猜你喜欢
        • 2013-05-31
        • 2014-07-11
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        • 2015-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多