How to push checkbox checked values to js object using jquery each function?

I want the checked checkbox values to store in food javascript object like below:

food: {
{id: 1, name: egg }
{id: 2, name: meat}
}

Here’s my code:

var exclude_foods = {};

jQuery('input[name=exclude_food]:checked').each(function(){
   exclude_foods = Object.assign(exclude_foods, {
     id: 1,
     name: jQuery(this).val(),
   });
});

Any suggestion or help?

>Solution :

You can use jQuery’s map() method to do what you require.

Note that it’s not clear where the id value is intended to come from, so I set it to the index of the checkbox for this example. This can easily be amended to suit your use case.

$('button').on('click', e => {
  var exclude_foods = {
    foods: $('input[name="exclude_food"]:checked').map((i, el) => ({
      id: i,
      name: el.value
    })).get()
  };
  console.log(exclude_foods);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<label>
   <input type="checkbox" name="exclude_food" value="egg" />
   Egg
</label>
<label>
   <input type="checkbox" name="exclude_food" value="meat" />
   Meat
</label>
<label>
   <input type="checkbox" name="exclude_food" value="nuts" />
   Nuts
</label>

<button>Get values</button>

Leave a Reply