Home > database >  Set other checkbox value & name when checkbox checked
Set other checkbox value & name when checkbox checked

Time:01-21

I want to set a checkbox value on the next block html code based on the first checkbox. When I click location loc checkbox, it will set the value to 0 & name for without-qr class. And when the loc checkbox is unchecked, the without-qr name would be removed.

I've tried like this, but still not working:

$(".loc").change(function() {
  if (this.checked) {
    $(this).closest('.p-without-qr').next().find('.without-qr').val(0);
    $(this).closest('.p-without-qr').next().find('.without-qr').attr('name', 'qr[]');
  } else {
    $(this).closest('.p-without-qr').next().find('.without-qr').removeAttr("name");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<dd >
  <ul >
    <li >
      <fieldset>
        <div >
          <input type="checkbox" name="location_id[]"  value="{{ $location->name }}" id="location">
          <label>
                  Location Name
               </label>
        </div>
      </fieldset>
    </li>
  </ul>
</dd>
<dd >
  <ul >
    <li >
      <fieldset>
        <div >
          <input type="checkbox"  id="{{ $loc->location_name }}">
          <label>
               Without QR
               </label>
        </div>
      </fieldset>
    </li>
  </ul>
</dd>

CodePudding user response:

please try this and change the closest function value for finding next block HTML

$(".loc").change(function() {
  if($(this).is(':checked')) {
     $(this).closest('dd').next().find('.without-qr').val(0);
     $(this).closest('dd').next().find('.without-qr').attr('name', 'qr[]');
  }else{
     $(this).closest('dd').next().find('.without-qr').removeAttr("name");
  }
});

CodePudding user response:

Your closest needs to go further

$(".loc").on("change", function() {
  const $nextDD = this.closest("dd").next(); 
  if ($nextDD) {
    const $withoutqr = $nextDD.find(".without-qr");
    if (this.checked) {
      $withoutqr.val(0);
      $withoutqr.attr('name', 'qr[]');
    } else {
      $withoutqr.removeAttr("name");
    }
  }
});
  •  Tags:  
  • Related