2
$('<input>', {
    type: "checkbox",
    id: "checkbox" + value.AttributeName,
    name: "checkbox" + value.AttributeName,
    className: required + " " + dataType,
    attributeId: value.AttributeId,
    disabled: readOnly,
    checked: (value.AttributeValue != "0") ? "true" : "false"
}).appendTo(li);

I am dynamically creating a checkbox element. I need to then assign the checked property to it or not. But In the code below, it's always checked because the property is present.

Help?

2 Answers 2

4

Don't use a string here, use a boolean:

$('<input>', {
    type: "checkbox",
    id: "checkbox" + value.AttributeName,
    name: "checkbox" + value.AttributeName,
    className: required + " " + dataType,
    attributeId: value.AttributeId,
    disabled: readOnly,
    checked: (value.AttributeValue != "0")
}).appendTo(li);

checked is a boolean property in the DOM, so a string of any non-0 length is "truey", meaning that "false" is really true. Instead set it directly to true or false, no strings.

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

2 Comments

That would be checked: value.AttributeValue != "0", without the ternary. :)
@Tomalak - +1 - trees/forest and such :)
1

Here's another option

$('<input>', {
    type: "checkbox",
    id: "checkbox" + value.AttributeName,
    name: "checkbox" + value.AttributeName,
    className: required + " " + dataType,
    attributeId: value.AttributeId,
    disabled: readOnly,
}).attr('checked',value.AttributeValue!="0")
  .appendTo(li);

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.