Get/Set Checkbox and Radio Button values using Prototype

29,063

Solution 1

I ended up writing my own extensions to Prototype to do this. You can see them on Github. Here's a note from the project:

"These extensions allow you to use Prototype’s convenient $F() syntax to get and set the values of these grouped input elements. They’ve been tested with Prototype 1.6.0.3 and 1.6.1. There are other bits in these extensions as well. See the README.html file for more details."

The answers from seengee and Los are much appreciated, but I wanted a more integrated solution that would allow me to work with checkboxes and radio buttons with the natural $F() syntax that I already use with other form elements.

Solution 2

You can always do something like this: (assumes you have your checkboxes have a class of checkboxes).

var checkedList = [];
$$('.checkboxes').each(function(ele){
   if( $(ele).checked )
   {
       checkedList.push($(ele).name);
   }
});

Solution 3

edit - just realised i misread the question, code below only good for setting values:

var form = $('options');
checkboxes = form.getInputs('checkbox');
checkboxes.each(function(e){ e.checked = 0 });
// or even checkboxes.invoke('checked',0);

could maybe use something like this though:

var cels = new Array();
$$('checkbox[checked="checked"]').each(el){
  cels.push(el.value);
}

Solution 4

This is only for radio buttons, but still useful.

Get

$$('input:checked[name="radio_name"]')[0].value

Set

$$('input[name="radio_name"][value="to_select"]')[0].checked = true

"radio_name" is the name of your radio group. "to_select" is whichever value you want to select. The "[0]" works because only 1 radio button can be checked at a time.

On a side note, I kinda don't like prototype. A lot easier in jQuery, but you gotta use what you gotta use.

Share:
29,063
Eric Nguyen
Author by

Eric Nguyen

Currently at Getaround.com. Convenient, low-impact access to transportation for those who choose not to own cars. Profitable, less-wasteful ownership for those who do. Formerly of Flux.io, Google, Google.org, Samasource.org, and Instructables.com.

Updated on June 28, 2020

Comments

  • Eric Nguyen
    Eric Nguyen about 4 years

    Prototype is great, but with the 1.6.1 release, the library still doesn't allow getting/setting of grouped inputs (checkboxes and radio buttons.) I'd like a way to get an array of selected values with $F($("form").checkboxes). I'd like to be able to set those checkboxes to an array of values, on the flip side.

    Ideas?