Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery, how can I select different elements by the name attribute?

I am trying to loop through some elements in a form (radios, text boxes, and select boxes) and get the value from each element. I am looping through by the name of each element (I don't think I can use ID because a group of radio buttons all have different IDs, but all have the same name).

Here are 2 selectors that encompass all the elements I need:

$("input[name=" + prop + "]")
$("select[name=" + prop + "]")

where prop is the loop iterator.

I want perform the same operation on both selectors, so I tried to combine them:

$("input[name=" + prop + "]", "select[name=" + prop + "]")

But that didn't work.

Is there a way to combine a search for both input elements and select elements in one selector?

Thanks!

like image 778
BrianH Avatar asked Dec 02 '22 06:12

BrianH


2 Answers

You have just one little mistake: You declared the two selectors as two different parameters instead of one parameter with the comma as part of the selector:

$("input[name=" + prop + "], select[name=" + prop + "]")

The way you wrote it uses the elements of the second selector parameter as the context the first selector parameter is resolved from.

like image 167
Gumbo Avatar answered Dec 03 '22 23:12

Gumbo


If the comma is included in the selector string it will work. You could also do

$("input, select").filter("[name=" + prop + "]")

which eliminates writing "[name=" + prop + "]" twice.

like image 27
Jacob Mattison Avatar answered Dec 04 '22 01:12

Jacob Mattison