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;
Thanxs..
It’s really working and simple.
Clean, concise example. This was helpful, thanks…
-Pete.
Hi mate, thanks for this – a unique compressed prototype :).
Hi there,
thanks for that tip I was getting mad with that!!
– Julio from Perú 😉
James Starmer » Blog Archive » How to find which radio button is selected
This is so beautiful it brings tears to my eyes. Thanks!
Nice one-liner solution to a common problem 🙂
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.
Thanks mate. Simple and impressive solution.
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'
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.
Here’s an alternative, note the form tag must have an ID
var typeValue = $(‘myform’).serialize().toQueryParams()[‘type’]
David Bolton Strikes Again » Blog Archive » Ajax.Autocompleter with dynamic parameters
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.
you could benefit from using the CSS selectors in stead like so:
$$(‘input[name=type]:checked’).first().value;
Short and simple 🙂
viz : Prototype Radio Button Serialization Bug
Obtener el valor de la selección de un grupo de radiobuttons con Prototype - 6th Edition
I like it. Thanks!
var form = $(‘MyForm’);
var typeValue = form.getInputs(‘radio’, ‘RadioName’).find(function(radio) { return radio.checked; }).value;