Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery create checked checkbox

Tags:

jquery

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.

like image 616
HamidRaza Avatar asked Dec 05 '25 08:12

HamidRaza


1 Answers

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');
like image 90
thecodeparadox Avatar answered Dec 08 '25 00:12

thecodeparadox