Populate multiple checkbox values by class

Viewed 62

How to populate multiple checkbox values to the same class elements fetched from the database with ajax. Checkbox values are comma-separated like this (apple, banana, orange).

$(document).ready(function(){
  var fruits = "banana,apple,orange";
  $(".check").val(fruits);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class"fruits">
<input type="checkbox" class="check" value="apple">
  <label> Apple</label><br>
  <input type="checkbox" class="check" value="orange">
  <label> orange</label><br>
  <input type="checkbox" class="check" value="banana">
  <label> Banana</label><br>
  <input type="checkbox" class="check" value="mango">
  <label> Mango</label><br>
</div>

2 Answers

$(document).ready(function(){
  var fruits = "banana,apple,orange";
  // Create an array with all the fruits
  var split = fruits.split(',');
  
  // Select each input by the value in this array
  split.forEach(f => {
    // Use the prop checked to check the boxes
    $('input[value="' + f + '"]').prop( "checked", true );
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class"fruits">
<input type="checkbox" class="check" value="apple">
  <label> Apple</label><br>
  <input type="checkbox" class="check" value="orange">
  <label> orange</label><br>
  <input type="checkbox" class="check" value="banana">
  <label> Banana</label><br>
  <input type="checkbox" class="check" value="mango">
  <label> Mango</label><br>
</div>

You can use split and includes:

$(document).ready(function () {
            var fruits = ("banana,apple,orange");
            var array = fruits.split(",");

            $('.check').each(function (i) {
                if (fruits.includes($(this).val()))
                   $(this).prop('checked', true);
            });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class"fruits">
<input type="checkbox" class="check" value="apple">
  <label> Apple</label><br>
  <input type="checkbox" class="check" value="orange">
  <label> orange</label><br>
  <input type="checkbox" class="check" value="banana">
  <label> Banana</label><br>
  <input type="checkbox" class="check" value="mango">
  <label> Mango</label><br>
</div>

Related