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
What happens, if you do this way:-
$('#new_user_form input, #new_user_form select').each(function(key, value) {
Refer LIVE DEMO
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
});
I'm using:
$($('form').prop('elements')).each(function(){
console.info(this)
});
It Seems ugly, but to me it is still the better way to get all the elements with jQuery
.
$('#new_user_form :input')
should be your way forward. Note the omission of the >
selector. A valid HTML form wouldn't allow for a input tag being a direct child of a form tag.
pure JavaScript is not that difficult:
for(var i=0; i < form.elements.length; i++){
var e = form.elements[i];
console.log(e.name+"="+e.value);
}
Note: because form.elements is a object for-in loop does not work as expected.
Answer found here (by Chris Pietschmann), documented here (W3S).
I have found this simple jquery snippet, to be handy for choosing just the type of selectors I want to work with:
$("select, input").each(function(){
// do some stuff with the element
});