tags:

views:

6267

answers:

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);
  });
});
+3  A: 

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...

Steve Losh
`.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).
thenduks
Oops, yeah, parent() will just return the direct parent. That's still probably not what he needs though. Editing my answer.
Steve Losh
+2  A: 

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( ... )
thenduks
.find() was the alternative I was looking for. Thanks!
Chris Bartow
A: 

I am trying to find something similar. I have a function i want to fire if no input has focus. But I can't seem to get it to work. Yes, I am very new to jQuery lol

var inputHasFocus = false;

$('#myForm :input').each(is(":focus")){

inputHasFocus = true;

};

if (inputHasFocus == false){ $("*").keypress(function (e) { // the function }); }

But I can't seem to get it to work what am I missing

Lance