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:


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:



Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.