Radio Buttons Simplified

Working with radio buttons in javascript has always been a pain, even with the help of jQuery. For example, if you have something like:

<label>Yes: </label>
<input type="radio" name="yes_no" value="yes"><br>
<label>No: </label>
<input type="radio" name="yes_no" value="no">

First, it is tedious, bordering non-trivial to get the get the current value of this radio selection group: is it yes or no?

Second, it is also tedious, bordering non-trivial to listen for changes to the value, especially given the different behaviors of different browsers(IE does not emit a change event when you click on a radio button to change it until you blur from it).

I wrote a tiny jQuery library to make this easier, with which you can do:

> $.radio('yes_no').val()
'yes'

to get the selected value, and to listen for changes:

> $.radio('yes_no').change(function(ui){
    console.log('yes_no value changed to ' + ui.val());
})

That's as simple as it gets. Code is as usual, on github.

blog comments powered by Disqus