0

Shouldn't this javascript just display an unchecked checkbox followed by the text "MyCheckBox"? Instead, it's just displaying "checked."

<html>
<head>
<script>
    var data = false;
    document.write('<input type="checkbox" ' + data ? "checked" : "" + '>MyCheckBox');
</script>
</head>
<body>


</body>
</html>
4
  • 1
    head element is not purposed to render any HTML. Also the ternary should be wrapped in the parentheses within a string concatenation. Commented Aug 8, 2017 at 22:52
  • You're missing parentheses Commented Aug 8, 2017 at 22:55
  • 1
    document.write('<input type="checkbox" ' + (data ? "checked" : "") + '>MyCheckBox'); just added parantheses Commented Aug 8, 2017 at 22:55
  • See <head>, only metadata content permitted. Commented Aug 8, 2017 at 22:59

3 Answers 3

1

Here's the correction:

document.write('<input type="checkbox" ' + (data ? "checked" : "") + '>MyCheckBox');

You were missing the parentheses.

Also, don't put that inside <head>, like Teemu said, you can't render HTML there.

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

1 Comment

Outstanding! I had no idea I had to do that.
0

Just Do This.

var data=false,
a=document.createElement("input");
a.setAttribute("type","checkbox");
a.checked=data;
document.body.append(a);

Comments

0

Even when you can have the desired result with this line:

document.write("<input type='checkbox' " + (data ? "checked" : "") + ">MyCheckBox");

It is not the best way, you are writing to a stream and that is a risky business. Handling in the structured way, you can do it in this way:

`var data = false;
var check=document.createElement("input");
check.id="mycheckbox"
check.type="checkbox";
check.checked=data;
document.body.appendChild(check)`

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.