views:

2116

answers:

2

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

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

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

Roman
+1  A: 

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');
    }
});
Jordan Ryan Moore
Still not working, but looks like it should. Is it possible bind() is flakier than onchange, even if less compatible. I'll keep playing around. Hmm.
Dakota R.
I ultimately eliminated the element-container class since it wasn't behaving for me and went with:$('.element-toggle input').bind('click', function () { var inputs = $(this).closest('li.form-item').find('input,select'); if ($(this).attr('checked')) inputs.attr('disabled', true); else inputs.removeAttr('disabled'); $(this).removeAttr('disabled');});Thanks again, D
Dakota R.