Coder Perfect

How do I choose an element in jQuery based on its name attribute?


In my web page, I have three radio buttons, as seen below:

When any of these three radio buttons is clicked, I want to get the value of the selected radio button in jQuery. Id (#) and class (.) selectors are available in jQuery, but what if I want to find a radio button by its name, like shown below?

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

Please assist me in resolving this issue.

Asked by Prashant

Solution #1

This should enough; all of this can be found in the documentation, which includes a very similar example:

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

I should also point out that in that excerpt, you have numerous IDs that are identical. This is a bad example of HTML. To group a set of elements, use classes rather than IDs, as IDs should be unique.

Answered by Paolo Bergantino

Solution #2

Try this to see which radio button is selected:

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

All of the radio buttons in the group will be notified of the event, and the value of the selected button will be stored in val.

Update: After posting, I decided that Paolo’s answer is superior because it requires one fewer DOM traversal. I’m keeping this response since it demonstrates how to get the selected element in a cross-browser compatible manner.

Answered by jeff.mitchel

Solution #3


Answered by Jay

Solution #4

another way


Answered by h0mayun

Solution #5

For me, this is ideal. If you have two radio buttons with the same “name,” for example, you only want the value of the checked one. You may give it a shot.

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

Answered by wdonayredroid

Post is based on