Getting Radio buttons value with Prototype.js

In Prototype.js, there’s a handy function $F to get the value of a form element.
However it doesn’t work well with a group radio buttons. The argument of $F is the id of the element, and since id is unique, we can’t use the name of the radio group to get the value, which is essentially how the server side gets the value.


<form name="myform">
<input type="radio" name="type" value="one"/>
<input type="radio" name="type" value="two"/>
<input type="radio" name="type" value="three"/>
</form>

#wrong
var typeValue = $F('type');

Here’s a quick solution.


var typeValue = Form.getInputs('myform','radio','type').find(function(radio) { return radio.checked; }).value;

Advertisement

19 thoughts on “Getting Radio buttons value with Prototype.js

  1. James Starmer » Blog Archive » How to find which radio button is selected

  2. I think the form has to have an id as well as a name in the opening form tag. I had to add id=”myform” to the form tag to get this working. Awesome tip! Thanks for posting.

  3. Thats very nice.

    Do you have an Solution as nice as this for doing the other way around?
    e.g.:
    setRadio( 'type', 'two' ) // checking the radio button wich value is 'two'

  4. Note to myself: Think before you write. 😀

    It was easy to do, taking your code as base.

    $('myform').getInputs('radio','type').find( function(radio){return radio.value=='two'}).checked = true;
    or
    Form.getInputs('myform','radio','type').find( function(radio){return radio.value=='two'}).checked = true;

    I like the first Version better because it looks more OO.

  5. David Bolton Strikes Again » Blog Archive » Ajax.Autocompleter with dynamic parameters

  6. Hi everyone:
    var typeValue = Form.getInputs(‘myform’,’radio’,’type’).find(function(radio) { return radio.checked; }).value;
    it can works in IE perfectly.However it doesn’t work in FireFox.

  7. viz : Prototype Radio Button Serialization Bug

  8. Obtener el valor de la selección de un grupo de radiobuttons con Prototype - 6th Edition

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s