Dakota
Dakota

Reputation: 79

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

Upvotes: 5

Views: 23331

Answers (4)

anon
anon

Reputation: 311

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.

Upvotes: 10

Rohit bal
Rohit bal

Reputation: 19

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

Upvotes: 1

Jordan Ryan Moore
Jordan Ryan Moore

Reputation: 6887

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

Upvotes: 4

Roman
Roman

Reputation: 4611

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

Upvotes: 0

Related Questions