skip to Main Content

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


  1. Chosen as BEST ANSWER

    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)
    })
    

  2. 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
    }
    
    Login or Signup to reply.
  3. 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);
    }
    
    Login or Signup to reply.
  4. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search