I want like this in javascript,when checkbox is visible show message1 else show message2.
-
you mean when checkbox is check show message one and when unchecked show message 2talha2k– talha2k2012-05-04 06:29:52 +00:00Commented May 4, 2012 at 6:29
-
What have you tried? Have you searched? Did you read the FAQ? How To Askpsycho– psycho2012-05-04 07:03:10 +00:00Commented May 4, 2012 at 7:03
-
2don't ask any question on getting ready made code without trying code, because stack-overflow is only for problems and solutions not for ready made code.Rahul Mandaliya– Rahul Mandaliya2013-04-13 14:21:32 +00:00Commented Apr 13, 2013 at 14:21
Add a comment
|
4 Answers
Try this:
HTML:
<label><input type='checkbox' onchange='handleChange(this);'>Checkbox</label>
JS:
function handleChange(cb) {
if(cb.checked == true){
alert('Message 1');
}else{
alert('Message 2');
}
}
JSBIN: http://jsbin.com/abukor/2
Hope this helps.
Comments
checkBox.onchange = function () {
console.log("Checked:" + checkBox.checked)
};
2 Comments
Pang
The requirement was
when checkbox is visible show message1 else show message2. This answer neither shows message1 nor message2. This answer is "wrong".Oded Breiner
@Pang I think the reader can figure out the
if on their own... checkBox.checked is a boolean.You can use the javascript ternary operator
var msg = ($("#MyCheckbox").is(":checked")) ? 'message1' : 'message2';
alert(msg);
You could of course in-line the ternary to make it really compact
Also checkout this SO answer for some other examples of using the ternary operator.
If you want to show the message if the checkbox itself is visible then you can use the :visible operator which would make the code:
var msg = ($("#MyCheckbox").is(":visible")) ? 'message1' : 'message2';
alert(msg);