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

Prashant picture Prashant · Jun 12, 2009 · Viewed 553.2k times · Source

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

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

Paolo Bergantino picture Paolo Bergantino · Jun 12, 2009

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.