3

When a select field is changed, I would like to loop through all of the input values in the form it belongs to using jQuery. This doesn't work below, but I can't figure out exactly how to do this.

$("select.mod").change(function(){
    $(this).parent().get(0).$(":input").each(function(i){
    alert(this.name + " = " + i);
  });
});
1
  • Can you post your HTML source or DOM structure for the form. Commented Jan 8, 2009 at 16:48

2 Answers 2

9

It's probably the selection of the "parent form" that's causing the problem.

The .parent() function returns just the immediate parent, which won't let you get the form element if your select.mod is nested in a <p> or something.

The .parents() function returns all the parents of the element; but the first one might not be the form tag. I'd try this:

$("select.mod").change(function(){
    $(this).parents('form') // For each element, pick the ancestor that's a form tag.
           .find(':input') // Find all the input elements under those.
           .each(function(i) {
        alert(this.name + " = " + i);
    });
});

That still might not help you if you have form elements nested inside each other, but if that's the case you've probably got bigger problems than a jQuery selector...

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

2 Comments

.parent() in this context returns only 1 element, the direct parent. In fact he doesn't need the get at all because jquery methods work on collections of objects (in this case, a collection of 1).
Oops, yeah, parent() will just return the direct parent. That's still probably not what he needs though. Editing my answer.
2

Your problem is almost certainly:

.$(":input")

That doesn't make sense. You're trying to call the $(":input") method on whatever .get(0) returns... of course there is no such method!

What you're looking for is probably more like:

$(this).parent().find(":input").each( ... )

Could offer more help with more details. Getting an error? What's the DOM structure? Etc.

Personally, I usually have id's on my forms. So I'd make things clea(r|n)er like:

$('#my_awesome_form :input').each( ... )

1 Comment

.find() was the alternative I was looking for. Thanks!

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.