0

Hey there I'm new to web developing and currently working on a project based on laravel framework. This is my code where all check boxes are displayed and based on database values they should be checked but I'm confuse in jquery side

Html Blade code:

@foreach ($param as $value)
<input type="checkbox" name="param1[]" id="param1" value="{{$value->id}}"
    <label>&nbsp;{{$value->parameters}}</label><br>
@endforeach

Here Values are 1,2,3,4,5 and data coming from db is 1,2,3 so only those are to checked

Here's my Jquery Code:

$(".edit").click(function() {

  $("#exampleModal1").modal('show');

  $tr = $(this).closest('tr');
  var data = $tr.children("td").map(function() {
    return $(this).text();
  }).get();
  $("#sub").val(data[2]);
  id = data[0];
  var _token = $('input[name="_token"]').val();
  console.log(_token);
  $.ajax({
    url: "{{route('admin.getparam')}}",
    type: "post",
    data: {
      "cp_id": data[1],
      "_token": _token
    },
    success: function(response) {
      var arr = $.parseJSON(response);
      //alert(arr);
      $.each(arr, function(i, v) {
        alert($('#param1').val());
        //alert(v);
      });
    }
  });
});

I need code to put only those check box checked please help

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Does this answer your question? [Setting "checked" for a checkbox with jQuery](https://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery) – Justinas Jul 20 '21 at 19:54
  • 1
    I see you are using same ID in all `foreach` - will never work in JS as ID must be unique – Justinas Jul 20 '21 at 19:55
  • Why isn't your `$.each()` loop using `i` or `v`? – Barmar Jul 20 '21 at 20:19
  • @Barmar Your Code is not working – Prashant Jani Jul 22 '21 at 06:50
  • Can you be more specific? Have you tried to do any debugging of it? Is the array coming from the DB integers or strings? You showed integers, so I convert the checkbox value to an integer before calling `.includes()`. – Barmar Jul 22 '21 at 13:39

1 Answers1

0

Iterate over the checkboxes, checking or unchecking them depending on whether the value is in the returned JSON array.

$.ajax({
  url: "{{route('admin.getparam')}}",
  type: "post",
  data: {
    "cp_id": data[1],
    "_token": _token
  },
  dataType: 'json',
  success: function(arr) {
    let checkboxes = $('input[name="param1\\[\\]"]');
    checkboxes.prop('checked', (i, cb) => arr.includes(+cb.value));
  }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612