0
<form id="form1" name="form1" method="post" action="">
  <input type="checkbox" id="check1" value="radio" />
  <label>left</label>
  <input type="checkbox" id="check2" value="radio2" />
  <label>right</label>
</form>

I would like to know if the checkbox is checked or not everytime someone clicks on it and then set a variable to the value yes.

if ($('#check1').attr('checked'); ){
var check1 = 'yes'; 
else 
var check1 ='no'
}

this is what I have so far and it doesn't work How do I return the value

4 Answers 4

7

You don't need an if-statement to do that. You can use .is(":checked") which will return true if checked and false if not. Assign that value directly to your variable instead of using an if-statement:

var check1;
$("#check1").click(function(){
   check1 = $(this).is(":checked");
});
Sign up to request clarification or add additional context in comments.

Comments

2

Try this :

$("#check1").is(':checked')

Comments

1

Check out this jsfiddle. http://jsfiddle.net/ReF4X/ Let me know if what I'm doing doesn't make sense to you.

In the future, when you have a JS problem you should make a JSfiddle and post it here. People will then revise it with a working solution.

Comments

1

in javascript, scope is only specific to a function. unlike most other languages, this means you should not define variables inside of if or else blocks.

you should be using prop instead of attr for the checked property (assuming the latest version of jquery)

lastly, you have an erroneous semicolon which is probably breaking the if statement.

try this instead:

var check1;
if ($('#check1').prop('checked')) {
    check1 = 'yes'; 
} else { 
    check1 ='no'
}

1 Comment

@Matt correct. javascript does NOT scope blocks like most other languages do, only functions.

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.