开发者

jQuery disable form element when checkbox is checked

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?

Here is my 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>

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


just a tidbit: since jquery 1.6 you should not use $(this).attr('checked') which is always true, but rather $(this).prop('checked').

it is also advisable to use $(this).prop('disabled') (to test whether the element is disabled), and $(this).prop('disabled', newState) rather than attr.


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


That was helpful. If anyone's looking for a plugin, here you go: http://s.technabled.com/jquery-foggle


<div class='element-container'> is not a parent for $('.element-toggle input') is your example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜