<Marc Qualie/>

Detect Selected Radio Input in JavaScript [Mootools]

A collegue brought up an interesting subject today at work; how do you detect which radio button out of set has been selected in JavaScript? This is the first time in a few years I've been stumped on a JavaScript question, so I was quite annoyed! The last time I used a radio button must have been on a MySpace voting pole widget back in the day. So I had my challenge, and I was determined to find out.

My first attempt was to access the button via it's name inside of a form, but this just seemed to "IE6" to me. Then I started thinking about IDs, but then each button would need an id, and that's just overkill. Surely there is a more simple way then a reference to the form and looping through each input with the name then checking for .selected==true; Luckily, thanks to Mootools there is!

A month or two I upgraded the company website to use the latest stable version of Mootools 1.3, and I'm so glad I did! This version of the framework includes the Slick Parser, which has to be one of my most loved and life saving pieces of script, which I use on a daily basis. I started to think of radio selection as an event, or a state, rather than a variable. Many of you reading this will know that Slick supports CSS3 Selectors, which includes pseudo events.

$$('#formid input[type=radio][name=test]:selected')[0]

Thanks to pseudo, I was able to grab the selected radio button via the above code. That snippet will get the reference to the radio input with name "test" in the form with ID "formid". There are many possibilities what you could use this for, but this is just an example. Hope this helps someone save some time.

If you have any questions about this post, or anything else, you can get in touch on Bluesky or browse my code on Github.