Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'); }); 
like image 586
Dakota Avatar asked Nov 25 '09 19:11

Dakota


People also ask

How do you check checkbox is enable or disable?

prop ("disabled", true | false); This function returns the Boolean value as if the parameter for this prop() function is specified as true then the selected element or checkbox object is disabled else if the parameter is set to false the checkbox object or any other selected element is not disabled.

How can check Div is disabled or not in jQuery?

Use $("#div1"). prop("disabled") to check whether the div is disabled or not.

How check textbox is disabled or not in jQuery?

You can use $(":disabled") to select all disabled items in the current context. To determine whether a single item is disabled you can use $("#textbox1").is(":disabled") .

How check if checkbox is checked jQuery?

prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes.


1 Answers

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.

like image 50
anon Avatar answered Sep 27 '22 22:09

anon