Reputation: 15111
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);
});
});
Upvotes: 3
Views: 21161
Reputation: 19862
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...
Upvotes: 9
Reputation: 30442
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( ... )
Upvotes: 2