-1

I want like this in javascript,when checkbox is visible show message1 else show message2.

Jui Test
  • 2,271
  • 13
  • 44
  • 71
  • you mean when checkbox is check show message one and when unchecked show message 2 – AlphaMale May 04 '12 at 06:29
  • What have you tried? Have you searched? Did you read the FAQ? [How To Ask](http://stackoverflow.com/questions/how-to-ask) – psycho May 04 '12 at 07:03
  • 2
    don'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 Apr 13 '13 at 14:21

4 Answers4

8

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.

AlphaMale
  • 23,514
  • 4
  • 57
  • 77
1
if($("#checkbox").is(":checked")){
    alert("message1");
}else{
    alert("message1");
}
august
  • 45
  • 9
1

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);
Community
  • 1
  • 1
Simon Martin
  • 4,027
  • 7
  • 54
  • 88
1
checkBox.onchange = function () {
    console.log("Checked:" + checkBox.checked)
};
Oded Breiner
  • 25,024
  • 9
  • 99
  • 66
  • The requirement was `when checkbox is visible show message1 else show message2`. This answer neither shows `message1` nor `message2`. This answer is "wrong". – Pang Jun 13 '16 at 01:19
  • @Pang I think the reader can figure out the `if` on their own... `checkBox.checked` is a boolean. – Oded Breiner Jun 13 '16 at 13:19