JavaScript and Radio Button Values

Sometimes I have to work on JavaScript code and it’s not something I really like much (why? well… 😉 ).

Ok, so some days ago I had to read the value of a currently selected radio button. And that’s not really trivial, it requires some lines of code, e.g., iterating over all radio buttons and checking each one if it has its checked flag set. And then reading the value of the checked element’s value attribute. Well, it’s a pain…

And then I found out (I read a hint on some other blog, unfortunately don’t remember the URL) how reading the value can be done easily in just one line of code. Great ;-).

You have to use prototype for this:

var selectedValue = $$('input:checked[type="radio"][name="radioName"]').pluck('value');

$$ is prototype’s CSS selector function. In the example, all checked HTML input elements with type=”radio” and name=”radioName” will be returned by this function. As there’s actually always just one radio element selected at a time, the function returns just one element of which the attribute value can be read directly.

So, now that’s easy. Just a little bit hard to remember if you rarly use JavaScript, like me. I’m sure in half a year I’ll not remember how it worked. That’s why I wrote this blog entry… ;-).

Comments are closed.