Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading