Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through all elements of a form jQuery

Tags:

jquery

loops

I was just wondering what the best way of looping through all the child elements of a form would be? My form contains both input and select elements.

At the moment I have:

success: function(data) {                 $.each(data.details, function(datakey, datavalue) {                     $('#new_user_form > input').each(function(key, value) {                         if($(this).attr('id') == datakey) {                             $(this).val(datavalue);                         }                     });                 });             } 

This only loops through the input elements of the form though and I want to include the select elements too:

I have tried:

$('#new_user_form > input, #new_user_form > select').each(function(key, value) { 

but this doesn't work. Does anyone know why this would be happening? Thanks!

like image 309
James Avatar asked Jan 02 '13 10:01

James


People also ask

How to get all input values in jQuery?

To iterate through all the inputs in a form you can do this: $("form#formID :input"). each(function(){ var input = $(this); // This is the jquery object of the input, do what you will });

How to loop through input jQuery?

The inputs can be filtered by specifying the :input selector in jQuery that selects every type of input on the element it is used. Next, we will use the each() method to iterate over the inputs to display the values or perform any operation as needed. Syntax: $('#id *').

How do I iterate through a div in jQuery?

jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element.

What is .each in jQuery?

The each() method in jQuery specifies a function that runs for every matched element. It is one of the widely used traversing methods in JQuery. Using this method, we can iterate over the DOM elements of the jQuery object and can execute a function for every matched element.


1 Answers

From the jQuery :input selector page:

Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

This is the best choice.

$('#new_user_form *').filter(':input').each(function(){     //your code here }); 
like image 79
Ohgodwhy Avatar answered Sep 21 '22 02:09

Ohgodwhy