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

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

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?

Please tell me how to solve this problem.


Solution 1:

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.

Solution 2:

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.

Solution 3:


Solution 4:

another way


Solution 5:

This works great for me. For example you have two radio buttons with the same “name”, and you just wanted to get the value of the checked one. You may try this one.

$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();

Solution 6:

The following code is used to get the selected radio button value by name