Here's my html that I'm using in a Django application:
<div id="mahal_questions" class="showHide_div">
{{soldier.mahal_status.label_tag}}
{{soldier.mahal_status}}
{{soldier.mahal_status.errors}}
{{soldier.mahal_program.label_tag}}
{{soldier.mahal_program}}
{{soldier.mahal_program.errors}}
<p>
{{soldier.mahal_id.label_tag}}
{{soldier.mahal_id}}
{{soldier.mahal_id.errors}}</p>
</div>
{{soldier.currently_serving.label_tag}}
{{soldier.currently_serving}}
<div id="currently_serving_questions" class="showHide_div">
{{soldier.idf_id.label_tag}}
{{soldier.idf_id}}
{{soldier.idf_id.errors}}
<p></p> <!--prevents the error message from running into the next label-->
{{soldier.army_unit.label_tag}}
{{soldier.army_unit}}
{{soldier.army_unit.errors}}
<p>{{soldier.tafkid.label_tag}}
{{soldier.tafkid}}
{{soldier.tafkid.errors}}</p>
</div>
I have two divs here that each include 3 fields. mahal_questions includes mahal_status, mahal_program and mahal_id currently_serving_questions includes idf_id, army_unit, and tafkid fields.
For some reason though, when I loop through my divs and within each div, loop through my elements, I only see the first two elements in each div. The last element is ignored. (I think this problem may have started when I added in some <p>
elements, but I'm not sure.)
Here's my js (the method is meant to loop through each div on the page and if the div is hiding, loop through the elements and erase their value on submit so the hidden fields' values don't get sent to the db):
$('#intake_form').submit(function() {
var showhideDivList = document.getElementsByClassName("showHide_div"); //To avoid errors on a page with no show/hides
if (showhideDivList.length > 0) {
//get each show/hide div
Array.from(showhideDivList).forEach(function (div) {
console.log(div);
//if this div is hidden
if ($(div).is(":hidden")){
// //for each element that is going to be shown/hidden within the div
var elements = $(div).children();
console.log("elements.length:" + elements.length);
for (var i = 0; i < elements.length; i++) {
var element = elements.eq(i);
console.log(element);
console.log("value", element.val());
element.val("");
console.log("value", element.val());
}
}
});
}
});
See Pointy's answer in the comments.
The problem was that I had the two "missing" fields wrapped in <p>
tags, so the .children() function was grabbing the <p>
s and not the elements within the <p>
s. Thank you, Pointy!
So to fix this, I just put <p></p>
before the mahal_id and tafkid fields to push their labels onto the line after the error messages and then they are directly under their respective divs and will be included in the results from the .children() function.