user3304303
user3304303

Reputation: 1043

How to change variable based on checkbox being checked or not?

I have a checkbox like this...

 <input type="checkbox" id="something" name="something" value="25" data-val="25" checked="checked" class="option">
    <label for="something">Something</label>

I want to have javascript/jquery code where every time that checkbox is checked or unchecked, it looks to see if its checked and assigns a value of 25 if it's checked, or 0 if its not checked. However, when I test by checking/unchecking, it just keeps spitting out 25. Why isn't it changing to 0 when I uncheck? Any ideas what I'm doing wrong?

$( document ).ready(function() {
    $('.option').on('change', function() {
       if ($('#something').attr('checked')) {
          var something = 25;
      } else {
          var something = 0;
      }
      console.log(something);
    });
});

Upvotes: 1

Views: 868

Answers (1)

The Process
The Process

Reputation: 5953

.attr() method returns string "checked" -Initial state of the checkbox, which doesn't change.
It will always be evaluated as true, and if condition will always run.

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

So using .prop() you can get true/false values:

$('.option').on('change', function() {
   var something;
   if ($(this).prop('checked')) {
        something=25;
      } 
    else {
        something = 0;
      }
        console.log(something);
 });

Or you can check if the checkbox is checked with .is() method which returns boolean.

$('.option').on('change', function() {
      var something;
       if ($(this).is(':checked')) {
          something=25;
      } else {
           something = 0;
      }
      console.log(something);
 });

Upvotes: 1

Related Questions