Reputation: 3538
when a checkbox on my page is clicked, I grab it's containing elements and append the whole block to another part of the page. Like this:
$('.favourite [type="checkbox"]').change(function () {
var check = $(this),
checked = $(check).attr("checked"),
id = $(check).attr("id").split("-")[1],
parent = $("#food-" + id),
parentContent = $("<div />").append($("#food-" + id).clone()).html(),
favelist = $(".favourites .content");
if (checked === "checked") {
$(favelist).append(parentContent);
}
});
I want the new checkbox to be checked when it is pasted into the favelist. Is there anything I can do to parentContent- which contains the HTML block of the checkbox & surrounding elements- so that it is already checked when it is appended?
Upvotes: 1
Views: 107
Reputation: 592
You don't need to append a string to favelist, you can append a jQuery element right away. By doing this, all properties and styling set through the DOM will be kept, such as checked
.
That means you can drop both $("<div />").append(
and ).html()
.
The resulting code would be the following.
$('.favourite [type="checkbox"]').change(function () {
var check = $(this),
checked = $(check).attr("checked"),
id = $(check).attr("id").split("-")[1],
parent = $("#food-" + id),
parentContent = $("#food-" + id).clone(),
favelist = $(".favourites .content");
if (checked === "checked") {
$(favelist).append(parentContent);
}
});
It will be faster as well.
Upvotes: 1
Reputation: 16369
I'll give this the old college try ...
$('.favourite').on('click','[type="checkbox"]',function(){
var chk = this.checked,
id = this.id.split("-")[1],
parent = $("#food-" + id),
parentContent = $("<div />").append($("#food-" + id).clone()).html(),
$favelist = $(this).find(".content");
if (chk === "checked") {
$favelist.append(parentContent).find('input[type="checkbox"]').prop('checked');
}
});
This adds a little delegation action, as well as uses the vanilla JS versions of checked
and id
for performance purposes. It also eliminates the double-wrapping you were doing with favelist
.
Upvotes: 0
Reputation: 40639
Try this,
checked = this.checked,
Or
checked = $(check).prop("checked"),
in place of
checked = $(check).attr("checked"),
And Codition like,
if (checked === true) {
$(favelist).append(parentContent);
}
Full code,
$('.favourite [type="checkbox"]').change(function () {
var check = $(this),
checked = this.checked,
id = $(check).attr("id").split("-")[1],
parent = $("#food-" + id),
parentContent = $("<div />").append($("#food-" + id).clone()).html(),
favelist = $(".favourites .content");
if (checked === true) {
$(favelist).append(parentContent);
}
});
Upvotes: 0