Mark
Mark

Reputation: 21

jQuery Checkbox dynamically created with checked property

$('<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?

Upvotes: 2

Views: 1267

Answers (2)

JohnFx
JohnFx

Reputation: 34917

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

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630607

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.

Upvotes: 4

Related Questions