当复选框被选中时,jQuery禁用表单元素 [英] jQuery disable form element when checkbox is checked

查看:151
本文介绍了当复选框被选中时,jQuery禁用表单元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a complicated jQuery form and I want to disable several form elements if a certain checkbox is checked. I'm using jQuery 1.3.2, and all the relevant plugins. What am I doing wrong here? Thanks, Dakota

这是我的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:

Here is my 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'); }); 


推荐答案

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

There are a few things that should be changed. First of all, the actual HTML structure doesn't match what you're querying for in JavaScript (specifically the parents() call). Secondly, binding to the click event will provide better support in IE since IE will sometimes wait to fire the change event until after the element loses focus.

$('.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');
    }
});

这篇关于当复选框被选中时,jQuery禁用表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆