Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery, how do I select an element by its name attribute?

I have 3 radio buttons in my web page, like below:

<label for="theme-grey">    <input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>  <label for="theme-pink">    <input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>  <label for="theme-green">    <input type="radio" id="theme-green" name="theme" value="green" />Green</label>

In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?

$("<radiobutton name attribute>").click(function(){}); 

Please tell me how to solve this problem.

like image 570
djmzfKnm Avatar asked Jun 12 '09 11:06

djmzfKnm


People also ask

How do I select an element by attribute name?

To select elements by an attribute name, pass a selector with the attribute's name to the querySelectorAll() method, e.g. document. querySelectorAll('[title]') . The querySelectorAll method will return a collection of the elements that have the provided attribute set.

What is the syntax to select an element with name?

The name attribute selector can be used to select an element by its name. This selector selects elements that have the value exactly equal to the specified value.

How do you find the value of an element with a name instead of ID?

Just type the name of the element without "<" and ">" characters. For example type P, not <P> if the answer is the <P> element.


2 Answers

This should do it, all of this is in the documentation, which has a very similar example to this:

$("input[type='radio'][name='theme']").click(function() {     var value = $(this).val(); }); 

I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.

like image 72
Paolo Bergantino Avatar answered Sep 30 '22 16:09

Paolo Bergantino


To determine which radio button is checked, try this:

$('input:radio[name=theme]').click(function() {   var val = $('input:radio[name=theme]:checked').val(); }); 

The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.

Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.

like image 40
jeff.mitchel Avatar answered Sep 30 '22 17:09

jeff.mitchel