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

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


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.


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