0

Checkbox value is change to 1 but when unchecked then it cannot be change to 0

$('.ChkBox').change(function() {
  if ($(this).attr('checked')) {
    $(this).val('1');
  } else {
    $(this).val('0');
  }
  alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked data-plugin="switchery" data-color="#648c2c" data-size="small" value="0" class="ChkBox" name="sms[]" />

In the alert I always get 1.

By default value is 0 and checked. I want it so that when the box is unchecked I get 1, and when checked I get 0. Please tell me where I am doing wrong.

j08691
  • 204,283
  • 31
  • 260
  • 272
Arslan
  • 433
  • 1
  • 5
  • 17

3 Answers3

1

Here you go with a solution

$('.ChkBox').change(function() {
  if ($(this).prop('checked')) {
    $(this).val('1');
  } else {
    $(this).val('0');
  }
  console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked data-plugin="switchery" data-color="#648c2c" data-size="small" value="0" class="ChkBox" name="sms[]" />

Instead of .attr please use .prop (property)

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
0

Instead of .attr you could put is(':checked') and ternary condition

$('.ChkBox').change(function() {
  $(this).val( $(this).is(':checked') ? '1' : '0' );
  console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked data-plugin="switchery" data-color="#648c2c" data-size="small" value="0" class="ChkBox" name="sms[]" />
alessandrio
  • 4,282
  • 2
  • 29
  • 40
0

Try this:

I have just used an onclick event inside the HTML and for debugging, I have used Jquery. You can remove the Jquery, if you don't need.

$(".ChkBox").on("change", function() {
var a = $(this).val();
alert(a);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked data-plugin="switchery" data-color="#648c2c" data-size="small" value="0" class="ChkBox" name="sms[]" onclick="$(this).attr('value', this.checked ? 1 : 0)"/>

hope this helps.

Harish ST
  • 1,475
  • 9
  • 23