Select all inputs of a given form in Jquery

房东的猫 提交于 2019-12-31 07:07:30

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/2088319/select-all-inputs-of-a-given-form-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!