-1

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

3
  • you mean when checkbox is check show message one and when unchecked show message 2 Commented May 4, 2012 at 6:29
  • What have you tried? Have you searched? Did you read the FAQ? How To Ask Commented May 4, 2012 at 7: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. Commented Apr 13, 2013 at 14:21

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

2
checkBox.onchange = function () {
    console.log("Checked:" + checkBox.checked)
};

2 Comments

The requirement was when checkbox is visible show message1 else show message2. This answer neither shows message1 nor message2. This answer is "wrong".
@Pang I think the reader can figure out the if on their own... checkBox.checked is a boolean.
1
if($("#checkbox").is(":checked")){
    alert("message1");
}else{
    alert("message1");
}

Comments

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

Comments

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.