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

Jquery to get array of objects based on checkbox values

I have multiple checkboxes in a html form
I need to get the array of objects when any of the checkboxes in the html form is checked or unchecked, that is when a change is made it has to return the array of objects

I prefer to use $.map

The expected value is

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

[{"A": "dataA"},{"B": "dataB"}] when both A and B are checked
[{"A": "dataA"}] when only A is checked
and so on

I have tried with

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

$('input[type="checkbox"]').change(function() {
    
alert($.map($("input[type='checkbox']:checked"), function(i) {
  var a = []
  a[$(this).attr("name")] = $(this).attr("data-id");
  return a
}));
});
});
</script>

<input data-id="dataA" name="A" type="checkbox" />A
<input data-id="dataB" name="B" type="checkbox" />B
</head>
</html>

>Solution :

You mean this?

Map is not a good match for what you want, and you abuse an array as an object.

Here is an object array

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {

      $('input[type="checkbox"]').change(function() {
        const res = []
        $("input[type='checkbox']:checked").each(function(i) {
          res.push({[$(this).attr("name")] : $(this).attr("data-id")});
        });
        console.log(res)
      });
    });
  </script>

  <input data-id="dataA" name="A" type="checkbox" />A
  <input data-id="dataB" name="B" type="checkbox" />B
</head>

</html>

And here is an object:

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {

      $('input[type="checkbox"]').change(function() {
        const res = {}
        $("input[type='checkbox']:checked").each(function(i) {
          res[$(this).attr("name")] = $(this).attr("data-id");
        });
        console.log(res)
      });
    });
  </script>

  <input data-id="dataA" name="A" type="checkbox" />A
  <input data-id="dataB" name="B" type="checkbox" />B
</head>

</html>
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