Select all inputs of a given form in Jquery

2020-05-08 17: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

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?

2条回答
The star\"
2楼-- · 2020-05-08 17:48

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.

查看更多
乱世女痞
3楼-- · 2020-05-08 18:01

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

查看更多
登录 后发表回答