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.
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.
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.
Just type the name of the element without "<" and ">" characters. For example type P, not <P> if the answer is the <P> element.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With