HamidRaza
HamidRaza

Reputation: 650

jquery create checked checkbox

How to create checked checkbox element with jquery?

I have tried with.

$('<input>', {
    type:"checkbox",
    "checked":"checked"
});

and

var input = $('<input>', {
    type:"checkbox"
});
input.attr('checked',true);

These are not working. the checkbox is remain unchecked after appending to element.

Upvotes: 3

Views: 12397

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

you have to append them to Document.

For example:

$('<input>', {
    type:"checkbox",
    "checked":"checked"
}).appendTo('body'); // instead of body you can use any valid selector
                     // to your target element to which you want to
                     // append this checkbox

The code

$('<input>', {
    type:"checkbox",
    "checked":"checked"
});

Just create an element but not append it to DOM. In order to append it to DOM you have to use append() / appendTo() / html() etc any one method.

In case of second snippet:

var input = $('<input>', {
    type:"checkbox"
});
input.attr('checked',true);

$('#target_container').append(input);

// Or

input.appendTo('#target_container');

Upvotes: 10

Related Questions