Prashant Prashant - 2 months ago 6
HTML Question

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.

Answer

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

$("input: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.

Comments