skip to Main Content

I’m having an error updating the checkbox when I return to the view containing it; in particular it always returns me the first checked checkbox but not the values selected before the update.

Can anyone help me to solve this problem?

<div class="mb-3">
  <div for="treatment" class="form-label">All treatments</div>
  @foreach ($treatments as $treatment)
      <input type="checkbox" id="{{$treatment->title}}" name="treatments[]" value="{{$treatment->id}}" {{ $treatment->id == 1 ? 'checked' : null }}>
      <label for="{{$treatment->title}}"> {{$treatment->title}}</label><br>
  @endforeach
</div>

2

Answers


  1. Chosen as BEST ANSWER

    I solved the following:

    <div class="mb-3">
      <div for="treatment" class="form-label">All treatments</div>
      @foreach ($treatments as $treatment)
          <input type="checkbox" id="{{$treatment->title}}" name="treatments[]" value="{{$treatment->id}}" @if (count($quote->treatments->where('id', $treatment->id))) checked @endif>
          <label for="{{$treatment->title}}"> {{$treatment->title}}</label><br>
      @endforeach
    </div>
    
    

  2. {{ $treatment->id == 1 ? 'checked' : null }}
    

    In this code, you only added ‘checked’ attribute if the $treatment->id is 1, so only the first checkbox will be checked.

    @foreach ($treatments as $key => $treatment)
        <input type="checkbox" id="{{$treatment->title}}" name="treatments[]" value="{{$treatment->id}}" {{ $treatment->id == $key ? 'checked' : null }}>
        <label for="{{$treatment->title}}"> {{$treatment->title}}</label><br>
    @endforeach
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search