Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mootools - how to get value of selected radio input type, from its name

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.

like image 258
philfreo Avatar asked Mar 06 '10 06:03

philfreo


2 Answers

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

like image 158
Anurag Avatar answered Nov 13 '22 00:11

Anurag


No need for

var value = $$('input[name=foo]:checked').getFirst().value;

Just use:

var value = $$('input[name=foo]:checked')[0].get('value');
like image 6
adasdasdas Avatar answered Nov 12 '22 23:11

adasdasdas