Varun
Varun

Reputation: 4452

Bootstrap Checkbox always return on

I am using bootstrap checkbox. the code for getting value and checkbox is bellow

    $( document ).ready(function() {
      
      var mycheckboxNewVal;
      
      var mycheckboxVal	= $('#mycheckbox').val();
      
      if(mycheckboxVal == 'on')
        {
          mycheckboxNewVal==1;
        }
      else
        {
          mycheckboxNewVal==0;
        }
          
      alert("mycheckboxNewVal :"+mycheckboxNewVal);

       
      
    });
    <div class="col-sm-1-5"><label class="control-label" for="pwd">Check Box </label></div>
      <div class="col-sm-1">
        <span class="button-checkbox">
    		<input type="checkbox" class="hidden" checked id="mycheckbox"/>
    		<button type="button" class="btn-chk" data-color="success"></button>
    	</span>
    </div>	

When I do 'alert("mycheckboxNewVal :"+mycheckboxNewVal);' I always get value 1.

Where am I making mistake?

Upvotes: 4

Views: 2539

Answers (2)

Jai
Jai

Reputation: 74738

You need to get the checked one:

$('#mycheckbox:checked').val();

Upvotes: 5

void
void

Reputation: 36703

Don't check for the value in case of checkbox, check for the checked property of checkbox.

  var mycheckboxVal = $('#mycheckbox')[0].checked;

  if(mycheckboxVal)
    {
      // Checkbox is checked.
      mycheckboxNewVal==1;
    }
  else
    {
      mycheckboxNewVal==0;
    }

Upvotes: 7

Related Questions