【问题标题】:jQuery disable form element when checkbox is checked选中复选框时jQuery禁用表单元素
【发布时间】:2010-12-20 10:23:28
【问题描述】:

我有一个复杂的 jQuery 表单,如果选中某个复选框,我想禁用几个表单元素。我正在使用 jQuery 1.3.2 和所有相关插件。我在这里做错了什么?

这是我的 HTML:

    <li id="form-item-15" class="form-item">
        <div class='element-container'>
            <select id="house_year_built" name="house_year_built" class="form-select" >
                 ...Bunch of options...
            </select>
            <input type="text" title="Original Purchase Price" id="house_purchase_price" name="house_purchase_price" class="form-text money" />
            <input type="text" title="Current Home Debt" id="house_current_debt" name="house_current_debt" class="form-text money" />
        </div>
        <span class="element-toggle">
            <input type="checkbox" id="house_toggle" />
            <span>Do not own house</span>
        </span>
    </li>

这是我的 jQuery:

$('.element-toggle input').change(function () { 
    if ($(this).is(':checked')) $(this).parents('div.element-container').children('input,select').attr('disabled', true);
    else $(this).parents('div.element-container').children('input,select').removeAttr('disabled'); }); 

【问题讨论】:

    标签: jquery forms checkbox jquery-events


    【解决方案1】:

    只是一个花絮:从 jquery 1.6 开始,您不应该使用$(this).attr('checked'),这始终是正确的,而应该使用$(this).prop('checked')

    还建议使用$(this).prop('disabled')(测试元素是否被禁用)和$(this).prop('disabled', newState)而不是attr

    【讨论】:

    • if 语句也可以省略,从而从 inputs.prop('disabled', $(this).prop('checked')); 生成单行符
    【解决方案2】:

    有一些事情需要改变。首先,实际的 HTML 结构与您在 JavaScript 中查询的内容不匹配(特别是 parents() 调用)。其次,绑定到 click 事件将在 IE 中提供更好的支持,因为 IE 有时会等到元素失去焦点后才触发 change 事件。

    $('.element-toggle input').bind('click', function () {
        var inputs = $(this).closest('li.form-item').find('div.element-container').children('input,select');
    
        if ($(this).attr('checked')) {
            inputs.attr('disabled', true);
        } else {
            inputs.removeAttr('disabled');
        }
    });
    

    【讨论】:

    • 仍然无法正常工作,但看起来应该可以。是否有可能 bind() 比 onchange 更脆弱,即使不那么兼容。我会继续玩。嗯。
    • 我最终消除了元素容器类,因为它不适合我并使用: $('.element-toggle input').bind('click', function () { var输入 = $(this).closest('li.form-item').find('input,select'); if ($(this).attr('checked')) inputs.attr('disabled', true ); 否则 inputs.removeAttr('disabled'); $(this).removeAttr('disabled'); });再次感谢,D
    【解决方案3】:

    这很有帮助。如果有人在寻找插件,请点击这里:http://s.technabled.com/jquery-foggle

    【讨论】:

    • 有效,但价格为 3 美元或 15 美元,并且不是开源的。
    【解决方案4】:

    &lt;div class='element-container'&gt; 不是 $('.element-toggle input') 的父级是你的例子

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 2020-10-21
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多