Sunday, October 9, 2011

jQuery: Checkbox howto

Once I've run into a project with a complicated form where some ajax didn't work. After digging into the code I've sadly seen a mistake that caused the functionality loss.

As you know, checkbox state can be determine at least two ways:
/* checkbox */
var chk1 = $('#chk1');   
               
chk1.attr('checked');
/* or */
chk1.is(':checked');

The previous programmer used the attr() function, however he forgot (or did not know...?) the difference between the two. While attr() function returns the attribute of the checkbox (undefined if not checked, 'checked' if checked), the second is() function returns boolean true or false. He sent the return value of attr() call as a string to a php script, but he expected 'true' or 'false', but he got 'checked' or 'undefined'.

/* checkbox */
var chk1 = $('#chk1');
chk1.attr('checked', true);

// returns 'checked' but it evaluates to boolean true in javascript
if(chk1.attr('checked')) {
    
}

// returns boolean true                
if(chk1.is(':checked')){
    
} 

Another note, to check a checkbox you can use:
chk1.attr('checked',true);

To uncheck a checkbox, you can do:
chk1.attr('checked', false);
/* or */
chk1.removeAttr('checked');

So the conclusion is to be careful out there and always know what a function will return!

No comments:

Post a Comment