0

I have some checkboxes generating through a foreach loop. All I want, by checking one checkbox another checkbox will be checked. I have already tried something like this,

This is the foreach block where the checkboxes are generating.

@foreach($testItems->where('category_id', $category->id) as $item)
  <div class="col-md-12">
    <div class='form-check'>
      <div class="custom-control custom-checkbox">
         <input type="checkbox"class="select-test form-check-input form-check-secondary" id="selectTest" name="test_name" value="{{$item->test_name}}">
      </div>
      <input type="checkbox" class="price" id="testPrice" name="test_price" value="{{$item->price}}" >
      <span>{{ucwords($item->test_name)}} ( {{$item->price}} )</span>
   </div>
</div>
@endforeach 

This is the script I tried

  var chk1 = $("#selectTest");
  var chk2 = $("#testPrice");
  chk1.on('change',  function(){
  chk2.prop('checked',this.checked);
  });

in this case, the first checkbox only works fine, but rest of them are not working.

N69S
  • 16,110
  • 3
  • 22
  • 36

1 Answers1

-1

It only works for the first checkbox only because id= attributes only match the first matching node in the DOM. Use a class (.selectTest) instead.

You may need to get rid of id="testPrice" as well or make it a class instead.


@foreach($testItems->where('category_id', $category->id) as $item)
  <div class="col-md-12">
    <div class='form-check'>
      <div class="custom-control custom-checkbox">
         <input type="checkbox"class="select-test form-check-input form-check-secondary selectTest" name="test_name" value="{{$item->test_name}}">
      </div>
      <input type="checkbox" class="price" name="test_price" value="{{$item->price}}" >
      <span>{{ucwords($item->test_name)}} ( {{$item->price}} )</span>
   </div>
</div>
@endforeach 

The jquery script.

 var chk1 = $(".selectTest");

  chk1.on('change',  function(){

      $(this).closest("div").next().prop('checked', $(this).is(":checked"));

  });

id attribute

The id global attribute defines an identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).

steven7mwesigwa
  • 5,701
  • 3
  • 20
  • 34