Using jQuery to count all inputs nested in div
I'm assuming you want to use jQuery, I've changed your HTML code a bit to make it work. Ids should be unique.
<div id="container">
<div class="field_shell">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="field"/>
</div>
<div class="field_shell">
<label for="age">Age</label>
<input type="text" name="age" id="age" class="field"/>
</div>
</div>
and the jQuery code to count for each #container
, It will traverse the DOM tree and return all elements that match input
var inputs = $("#container").find($("input") );
console.log(inputs.length)
If you want to check for filled input elements, you can look at the element.length
property. To count for multiple containers, you could run a loop to handle each #container
and nest the code above in it.
Alix Përry
Updated on June 04, 2022Comments
-
Alix Përry almost 2 years
I have a setup basically like this:
<div id="container"> <div class="field_shell"> <label for="name">Name</label> <input type="text" name="name" id="name" class="field"> </div> <div class="field_shell"> <label for="age">Age</label> <input type="text" name="age" id="name" class="field"> </div> </div>
Except on a larger scale, there are three sets of
#container
, each#container
holding several (and varying amounts of) div.field_shell elements. Most div.field_shell hold only one input, but a few do hold two separate input elements.My issue is how I can count the number of input elements in each #content. Bonus points for giving some insight on the best method of checking if each input in each #container div is filled, and returning specific results if so.
I assume
.length
is viable here, but I am stumped. Especially on checking the "status" of each#container
(by status, I mean if each input within that#container
is filled, and not empty).Thank you guys so much for reading through, and thank you more for helping :)