I have a html structure that looks like the following:
<div>
<div questionName="${data.Name}" class="item">
<div class="left"><input type="checkbox" class="include-checkbox"/></div>
<div class="center">{data.Name}</div>
<div class="right"><input class="comment" placeholder="Comment (optional)"/>
</div>
...
</div>
With multiple "items" (divs with class="item"). These are generated. Using jQuery, I need to go through those divs, and if the checkbox for that item is checked, add the value from the center div and input value from the right div as a key-value pair to an object (or a JSON string). So my resulting object should look like this:
{
"an item" : "some comment the user typed in",
"another item": "some other comment",
"yet another item" : ""
}
the comment is optional, and if the user doesn't fill anything in it should just contain empty string.
I am able to get all the items, because they have the same class, and run a foreach on them:
function submitItems() {
let items = {};
$('.item').each(function() {
?
});
}
But how do I then access the elements within the item? For example I want to check the status of the checkbox, but when I do $('.include-checkbox') it will give me all of them, not just the one that's inside my element. Also the function within the .each() construct, seems to have its own scope so the items object is not visible.
I have control over how the generated html looks, so I can add classes, ids or other attributes if need be.
.each()callback the "item"<div>elements will be referred to bythis, so you can use$(this).find(".center")for example..find()documentation.querySelectorAll()in most cases, so it'll be perfectly fine. I don't know where people get browser performance ideas from but modern browsers on computers less than 10 years old are extremely fast.