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.

2
  • Use if ($(this).is(':checked')) Commented Apr 16, 2018 at 13:36
  • thanks for the help @j08691 Commented Apr 16, 2018 at 13:38

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Explaining why he should use prop instead of attr would be great.
thanks for the help. now its working
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[]" />

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.