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!
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 });
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 *').
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.
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.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With