cppit
cppit

Reputation: 4564

jQuery checked radio button value

<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

Upvotes: 0

Views: 584

Answers (4)

jbabey
jbabey

Reputation: 46647

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'
}

Upvotes: 1

JohnColvin
JohnColvin

Reputation: 2509

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.

Upvotes: 1

KutePHP
KutePHP

Reputation: 2236

Try this :

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

Upvotes: 2

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

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");
});

Upvotes: 7

Related Questions