O'Reilly logo

jQuery Cookbook by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

10.2. Disabling and Enabling Form Elements

Problem

Your order form has fields for both shipping and billing contact information. You’ve decided to be nice and supply the user with a checkbox that indicates the user’s shipping information and billing information are the same. When checked, the billing text fields should be disabled:

<fieldset id="shippingInfo">
    <legend>Shipping Address</legend>

    <label for="shipName">Name</label>
    <input name="shipName" id="shipName" type="text" />

    <label for="shipAddress">Address</label>
    <input name="shipAddress" id="shipAddress" type="text" />
</fieldset>

<fieldset id="billingInfo">
    <legend>Billing Address</legend>

    <label for="sameAsShipping">Same as Shipping</label>
    <input name="sameAsShipping" id="sameAsShipping" type="checkbox" 
value="sameAsShipping" />

    <label for="billName">Name</label>
    <input name="billName" id="billName" type="text" />

    <label for="billAddress">Address</label>
    <input name="billAddress" id="billAddress" type="text" />
</fieldset>

Solution 1

If all you want to do is disable the billing fields, it’s as simple as using the jQuery .attr() and .removeAttr() methods when the change event is triggered:

// find the "sameAsShipping" checkbox and listen for the change event $('#sameAsShipping').change(function(){ if( this.checked ){ // find all text inputs inside billingInfo and disable them $('#billingInfo input:text').attr('disabled','disabled'); } else { // find all text inputs inside billingInfo and enable them $('#billingInfo input:text').removeAttr('disabled'); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required