jvance.com

.net, c#, asp.net, linq, htpc, woodworking

Get Value of Checkbox using jQuery to Enable Button

Posted in jQuery by JarrettV on 7/14/2009 3:58:00 PM - CST

Reading the value of a checkbox in jQuery is not obvious.  You must use a special selector :checked and then check if the value is undefined.

//checked
var checked = $('input[type=checkbox]:checked').val() != undefined;

//unchecked
var unchecked = $('input[type=checkbox]:checked').val() == undefined;

The typical use case for this code is when you want the user to check the "I agree to the terms and conditions" before they can continue. For example:

$(function() {
  $('#agree').click(function() {
    var satisfied = $('#agree:checked').val();
    if (satisfied != undefined) $('#continue').removeAttr('disabled');
    else $('#continue').attr('disabled', 'disabled');
  });
});

The above code finds the checkbox and binds to the click event.  When the user checks or un-checks the checkbox, it finds the continue button and enables or disables it based on the value of the checkbox.

Update - A more elegant way

//checked
var checked = $('input[type=checkbox]').is(':checked');

Change Textbox Readonly Value via Checkbox using jQuery

Another case you may want to enable or disable a textbox based on the value of the checkbox.

$(function() {
  $('#isOther').click(function() {
    var other = $('#isOther:checked').val();
    if (other != undefined) $('#other').removeAttr('readonly');
    else $('#other').attr('readonly', 'readonly');
  });
});

The above code changes the readonly property on the textbox when the checkbox is changed by the user.

Comments

Gravatar
Posted by Homer on 12/10/2009 8:47:09 AM - CST
or how about...
//checked var checked = $('input[type=checkbox]').attr('checked');
Gravatar
Posted by Bob F on 11/3/2011 1:21:54 PM - CST
Thanks. Helped me out.

Add Comment

Login using
GoogleYahooflickrAOL
and more
Or provide your details
Please enter your name. Please enter a valid email. Please enter a valid website.
Please supply a comment.
4.2 (31)
on 11/19/2009 10:36:56 AM - CST

Recent Entries

Valid XHTML 1.0 Strict
© Copyright 2016 Powered by AtomSite 1.3.0.0