-3

I have four checkbox like below

<label> <input type="checkbox" id="ca" value="0" name="ca"> CA </label>
<label> <input type="checkbox" id="nv" value="0" name="nv"> NV </label>
<label> <input type="checkbox" id="tx" value="0" name="tx"> TX </label>
<label> <input type="checkbox" id="fl" value="0" name="fl"> FL </label>

When user checks/unchecks each checkbox, it should change the value of the corresponding checkbox (check = 1 and uncheck = 0)

I know that I can do it by writing code separately for each checkbox.

But, I would like to know if we can write it in a single line (or in less lines) using jQuery

Jeff
  • 235
  • 6
  • 16

1 Answers1

2

You could bind a "change" listener to each checkbox. See jQuery's .on() and .change().
Then set the "changed" checkbox's value based on whether it's checked or unchecked.

Below, I've used JavaScript's this keyword to reference the checkbox that was clicked and a ternary operator to set its value according to its "checked" status.

jQuery('input[type=checkbox]').on('change', function() {
  this.value = this.checked ? 1 : 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" id="ca" value="0" name="ca">CA</label>
<label><input type="checkbox" id="nv" value="0" name="nv">NV</label>
<label><input type="checkbox" id="tx" value="0" name="tx">TX</label>
<label><input type="checkbox" id="fl" value="0" name="fl">FL</label>
showdev
  • 28,454
  • 37
  • 55
  • 73