I have a form with checkbox and I get the jQuery object after submitting the form having the checked input elements.
var $form = $(e.currentTarget);
var $inputs = $form.find("input.form-check-input:checked")
The inputs looks like this:
inputs = {
"0": {<input class="form-check-input" type="checkbox" value="" id="/api/memory/23/" checked="checked">...},
"1": {},
"2": {},
"3": {},
"length": 4,
"prevObject": {
"0": {
"0": {},
"1": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
"10": {},
"11": {}
},
"length": 1
}
}
I have to extract the ID of input element in the inputs
variable. I tried doing the following approaches but I get only the ID of element key like 0
, 1
. What I am missing here?
for (const entry in $inputs) {
console.log(entry.id) // Outputs 0, 1, 2, 3, 4..
}
$inputs.forEach((entry) => {
console.log(entry.id) // Outputs: TypeError: inputs.forEach is not a function
})
4
Answers
I was able to iterate the object of objects with help of
Object.entries
This worked for me:
for ... in
loops work slightly differently. They loop through the object’s keys, not its values.Try this:
The jQuery equivalent of
forEach
is calledeach
.Alternatively you can loop through the elements with
for...of
.Does
$(e.currentTarget).find("input.form-check-input:checked").attr('id')
not work?It’s been my experience that if a Selector returns a single Item 99% of the time it’s acts like you selected it by ID