Home > other >  Check/Uncheck checkbox depend on value match
Check/Uncheck checkbox depend on value match

Time:04-15

How can we get a checkbox checked only if a dynamic value matches the checkbox value in one line without applying if condition. otherwise uncheck checkbox,.

var checkVal = 'red';
$('#black:input[value="' checkVal '"]').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <input  type="checkbox" value="black" id="black" checked>
  <label  for="black">
    Black
  </label>
</div>

CodePudding user response:

Just compare the value in your prop:

var checkVal = 'red';
var $element = $('#black');
$element.prop('checked', $element.val() === checkVal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <input  type="checkbox" value="black" id="black" checked>
  <label  for="black">
    Black
  </label>
</div>

CodePudding user response:

!= as per @DarkBee works here, something I didn't know as well.

var checkVal = 'red';
$('input[value!="' checkVal '"]').prop('checked', false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <input  type="checkbox" value="black" id="black" checked>
  <label  for="black">
    Black
  </label>
</div>

var checkVal = 'black';
$('input[value="' checkVal '"]').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <input  type="checkbox" value="black" id="black" checked>
  <label  for="black">
    Black
  </label>
</div>

  • Related