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 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
})
CodePudding user response:
The jQuery equivalent of forEach
is called each
.
$inputs.each((index, entry) => {
console.log(entry.id);
});
Alternatively you can loop through the elements with for...of
.
for (const entry of $inputs) {
console.log(entry.id);
}
CodePudding user response:
for ... in
loops work slightly differently. They loop through the object's keys, not its values.
Try this:
for (const entry in $inputs) {
console.log($inputs[entry].id) // Should output the id
}
CodePudding user response:
I was able to iterate the object of objects with help of Object.entries
This worked for me:
Object.entries($input).forEach(([key, val]) => {
console.log(key, val.id)
})
CodePudding user response:
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