How to select a radio button or checkbox(es) with jQuery .val()

The jQuery API page for .val() doesn’t make it super clear how to set values for checkbox and radio button elements – but it can easily be done! In doing some research for form development for Everpurse, I noticed the array syntax used in the parameters passed to .val() in jQuery’s documentation examples. For example:

$('input[type="checkbox"]').val(['value1', 'value2']);

Note the square brackets around the parameters passed to .val(). This is because .val() expects an array for values being assigned to radio button, checkbox, and multiple-select form elements. I have no idea why it chooses to use an array even for radio button elements – which can only have one option selected at a time – but for now, it appears that this is the only way to get value assignment to work in jQuery.

Hope this clears things up – especially for those who’ve come across countless online posts recommending that you set the checked attribute to true. (Perhaps their advice is based on an older version of jQuery…?)