开发者

Select all inputs of a given form in Jquery

开发者 https://www.devze.com 2022-12-16 15:19 出处:网络
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

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 c开发者_如何学Pythonomplicated, 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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消