Tag Archives: radiobutton

Jquery: How to Set the Selected Radio Button via a Script Programming 10 FEB 2012

If you develop websites and work with JavaScript, but have never heard of jQuery before, then it is probably best that you start reading up on it right now. After all, as they like to put it themselves, jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript!

Now we’ve seen that to retrieve the value of the checked radio button from a group of radio buttons using jQuery, we need to use the input[]:checked selector and then grab the val string as you would normally do.

In practice, this process would look like this:

alert($('input[name=myradiobuttons]:checked').val());

Now sometimes you need to programmatically set the selected radio button in your JavaScript script, and thankfully jQuery once again comes to our rescue with its handy selectors.

If we know the value of the radio button to be selected, we can use the same trick as the above sans the :checked segment, and then filter those results with our known value, before finally ending off the selector with the act of setting the checked property.

In practice this would be set out like so:

$('input[name=myradiobuttons]').filter('[value=selectedvalue]').prop('checked',true);

Clever.

jQuery: How to Locate the Selected Radio Button out of a Group of Radio Buttons CodeUnit 13 MAY 2011

If you develop websites and work with JavaScript, but have never heard of jQuery before, then it is probably best that you start reading up on it right now. After all, as they like to put it themselves, jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript!

Radio buttons are pretty awesome when you need to ensure that a user has picked ONE of the given options presented to them, and using jQuery, it turns out to be a pretty simple affair to determine and manipulate exactly which radio button is currently selected from the group.

An example:

/* Your HTML...
<input type="radio" name="sample" value="1" />
<input type="radio" name="sample" value="2" checked="checked" />
<input type="radio" name="sample" value="3" />
*/

    // displays the selected radio button in an alert box
    alert($('input[name=sample]:checked').val());

The above will correctly select the selected radio button Sample 2 and will alert its value of… well 2.

The ‘input[name=sample]:checked’ jQuery selector is guaranteed to return us a result and of course, this result can be manipulated in which ever way you would like, as with any other jQuery selected DOM object.

Nifty.