views:

26

answers:

2

I have a form object in jquery, and I'd like to select all inputs of this form.

Let's suppose my form object is called form. If the form has an id, I can just do

var id = form.attr('id');
var inputs = $('#' + id + ' input');

If not I can check this, and then manually add a temporary id, do the selection, and remove the id (or just leave it there). But this just looks too complicated, there must be an easier way, but I'm not able to find it.

Another possible way (which I'm not able to make work) would be something like

var inputs = $('input').filter(function() {
    var parents = this.parents();
    return ($.inArray(form, parents) != -1);
});

but this too seems complicated (and it doesn't work as stated).

By the way, from the performance point of view, which approach would be more convenient?

A: 

Im not sure what you are trying to do here... if there are multiple forms on the page then you have to have some kind of identitfier.. a pernt, and id, a class something. If you only have a single form then its as simple as $('form input').

prodigitalson
Of course I have more than one form. The form is already identified by a particular jquery object, which I called (possibly confusing) form in the example code.
Andrea
ahhh ok... id dint catch that as a var mys mistake! in that case a simple `$('input', form)` should work where `form` is the variable for the form element you speak of.
prodigitalson
+1  A: 

http://docs.jquery.com/Traversing/find

form.find('input')

should do the trick I would think. Just in case, if you're trying to get all of the input fields to grab their current values and submit them with AJAX you can just use the .serialize method of your form:

data: form.serialize(),

As far as your performance question goes, I believe your first method is more effecient, the second will iterate over every input on the page. As of jQuery 1.4 the first method is definitely more efficient, querying based off of object IDs initially has been significantly enhanced.

Cryo
How come I never realized the existence of the find() method? This is exactly what I was looking for, thank you.
Andrea
If you haven't seen it yet: http://visualjquery.com/. I've found that site to be invaluable when trying to find the exact function I'm looking for.
Cryo