How an I get all form elements (input, textarea & select) with jQuery?

Edit: As pointed out in comments (Mario Awad & Brock Hensley), use .find to get the children

$("form").each(function(){
    $(this).find(':input') //<-- Should return all input elements in that specific form.
});

forms also have an elements collection, sometimes this differs from children such as when the form tag is in a table and is not closed.

var summary = [];
$('form').each(function () {
    summary.push('Form ' + this.id + ' has ' + $(this).find(':input').length + ' child(ren).');
    summary.push('Form ' + this.id + ' has ' + this.elements.length + ' form element(s).');
});

$('#results').html(summary.join('<br />'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="A" style="display: none;">
    <input type="text" />
    <button>Submit</button>
</form>
<form id="B" style="display: none;">
    <select><option>A</option></select>
    <button>Submit</button>
</form>

<table bgcolor="white" cellpadding="12" border="1" style="display: none;">
<tr><td colspan="2"><center><h1><i><b>Login
Area</b></i></h1></center></td></tr>
<tr><td><h1><i><b>UserID:</b></i></h1></td><td><form id="login" name="login" method="post"><input
name="id" type="text"></td></tr>
<tr><td><h1><i><b>Password:</b></i></h1></td><td><input name="pass"
type="password"></td></tr>
<tr><td><center><input type="button" value="Login"
onClick="pasuser(this.form)"></center></td><td><center><br /><input
type="Reset"></form></td></tr></table></center>
<div id="results"></div>

May be :input selector is what you want

$(“form”).each(function(){
$(‘:input’, this)//<– Should return all input elements in that specific form.
});

As pointed out in docs

To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(“:input”).

You can use like below,

$("form").each(function(){
    $(this).filter(':input') //<-- Should return all input elements in that specific form.
});

Leave a Comment