Question 1: Given
<input type="radio" name="foo" value="1" />
<input type="radio" name="foo" value="2" />
<input type="radio" name="foo" value="3" />
In Mootools, how do I return "2" given an input of "foo", assuming that the second radio button was clicked.
Question 2: (it's related)- Given similar checkbox inputs, how do I return either an array or comma separated list of the checked values?
I'm wanting to submit the values of these inputs via Request.JSON, passing it as a GET parameter.
Assuming the name of the checkbox is "foo", to get the selected radio item, you can use:
var values = $$('input[name=foo]:checked').map(function(e) { return e.value; });
This returns an array with 1 item, being the selected elements' value.
Or just extend an Array's prototype, and add a getFirst() method.
Array.implement({
getFirst: function() {
if(this.length == 0) {
return null;
}
return this[0];
}
});
Then you could do this:
var value = $$('input[name=foo]:checked').getFirst().value;
Similarly, to get all checked checkboxes, use:
var values = $$('input[name=foo]:checked').map(function(e) { return e.value; });
The double dollar ($$) function is used to select multiple elements with a CSS selector. Then a map (part of Array class) can be applied to those elements to get just the needed value(s).
You can read more about these pseudo-selectors at http://mootools.net/docs/core/Utilities/Selectors