Friday, August 6, 2010

2:25 AM
jQuery is a Javascript framework which can simplify coding Javascript for a website and removes a lot of cross browser compatibility issues.  Today's post looks at how to tell if an HTML form checkbox is checked or not checked with jQuery and then how to change it to be un/checked.

Our example form looks like this:

<input type="checkbox" name="foo" value="bar" />
<input type="button" onclick="show_checked()" value="Show" />
<input type="button" onclick="set_checked(true)" value="On" />
<input type="button" onclick="set_checked(false)" value="Off" />

There's checkbox with name "foo" and then three buttons. The first calls a functionto show us if the checkbox is checked or not, and the second two change it from being checked to not being checked.
There are several ways to get to work out if a checkbox is checked or not with jQuery, and here a couple of alternatives. Each will return true if it's checked or false if it's not.


We can change the status of the checkbox using the attr() function like so, to check the box:

$('input[name=foo]').attr('checked', true);

and like so to uncheck the box:

$('input[name=foo]').attr('checked', false);


Unknown said...

Please use another way to display your code because now is very hard to read.
Your blog is great!