2

It's doesn't work ( Why? Can anybody explain, please

function checkBox()
    {
        if($('.checkbox').prop('checked', true))
        {
            $('body').css('background','yellow');
        }
        else if ($('.checkbox').prop('checked', false))
            $('body').css('background','blue');
    }
1
  • html <input class="checkbox" type="checkbox" checked/> Commented Apr 1, 2015 at 13:41

2 Answers 2

1

.is() - Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

   if($('#checkbox').is(':checked')){
      $('body').css('background','yellow');
    }
    else{
      $('body').css('background','blue');
    }
Sign up to request clarification or add additional context in comments.

1 Comment

please make sure your event is triggered or not
0

FIDDLE: https://jsfiddle.net/7rpeL2gu/4/

Thats the answer HTML:

<input class="checkbox" type="checkbox" />

JS:

$(document).ready(function(){
  $('.checkbox').on('click', function(){
    checkBox( $(this) );
  });
});

function checkBox($this){
  if( $this.prop('checked') ){
      $('body').css('background-color','yellow');}
  else{
      $('body').css('background-color','blue'); }
}

P.S. Your code does not work, because $(input).prop('checked', true) - set input to checked, but $(input).prop('checked') give you input.state of checked.

P.P.S read this https://api.jquery.com/prop/

6 Comments

if i create function such as function checkBox(), i have mistake Uncaught TypeError: undefined is not a function
wait a second, i re-write code now for function calling
snx ( You helped me a lot
@Viktory try that way
You forget to include jquery - i update your fiddle: jsfiddle.net/4kzvnyky/1
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.