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

Using Foreach or another function to reduce the amount of code

please help. I have such a code with Checkboxes. I need to shorten it, namely to go through it through Foreach.
If you can shorten it in another way, then please write it..

let FormData = {
   DisplayName: $("#DisplayName").is(":checked"),
   Department: $("#Department").is(":checked"),
   Post: $("#Post").is(":checked"),
   Phone: $("#Phone").is(":checked"),
   Location: $("#Location").is(":checked"),
   Dinner: $("#Dinner").is(":checked")
} 
console.log(JSON.stringify(FormData));

I haven’t really tried anything yet. But I didn’t really find the answer I needed..

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 :

If you don’t know the names of the checkboxes and you want to perform this operation of collecting their state on all the checkboxes of a form, you can use this code.

var jsonObject = {};

// For each checkbox - Feed Json object
$('input[type=checkbox]').each(function(index){ jsonObject[$(this).attr('id')] = $(this).is(':checked'); });

console.log(JSON.stringify(jsonObject));

The principle is to use a selection of the checkboxes present on the page to then perform a loop on this selection and recover for each of the boxes their ID and their state.

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