Get Value of Checkbox using jQuery to Enable Button
Posted in jQuery by JarrettV on 7/14/2009 3:58:00 PM - CSTReading 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
Posted by Homer on 12/10/2009 8:47:09 AM - CST
//checked var checked = $('input[type=checkbox]').attr('checked');
Posted by Bob F on 11/3/2011 1:21:54 PM - CST