4

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!

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow - I totally see what I did wrong. I had copied and pasted the 2 selectors to make 1 selector, and I totally messed up on my quotes placement. Thanks for catching that!
You may also want to add textarea, and conceivably button.
5

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.

Comments

4

Don't try to shoehorn everything you do into jQuery. The DOM Level 1 HTML standard gives you HTMLFormElement.elements, which is easy, fast and doesn't fail for unusual characters in name like a selector string would.

<form id="x" ...>
    <input type="text" name="foo" />
    <select name="foo"></select>
</form>

<script type="text/javascript">
    var prop= 'foo';
    var form= $('#x')[0];
    var foos= form.elements[prop];
    alert(foos.length+' '+foos[0].type+' '+foos[1].type);  // 2 text select-one
</script>

2 Comments

That's a good tip - I fall into that trap a lot, actually. It's good to take a step back and remember the language that jQuery is written in.
As a bonus, this will catch other form fields that aren't inputs or selects (like a textarea), in case the form is changed somewhere down the road.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.