I was writing a code to append a card with a new header every time a button is pressed also the header is dynamically providing by user. the problem is i cant make the function work properly for more than one card. I know the problem is that every card has the same class hence the new header will be appended to each card.I also want to add different user input lists to these cards.
$(".add").click(function(){
let list = $("#userInp").val()
$("#mainCard").append('<div ><div id ="head" ></div><div ><ul></ul></div></div>')
$("#mainCard").find("#head").append('<button type = "checkbox" class ="form-check-input" id = "checkbox01"></button>' list '')
})
This is my code.And thanks for helping me.
CodePudding user response:
You can skip the head id all together. Work with a document fragment and you are contained to working with just what you are adding.
NOTE the code below is untested and may need some tweaking.
$(".add").click(function(){
//Create the fragment
let frag = new DocumentFragment();
let list = $("#userInp").val();
//Append the card to the fragment
$(frag).append('<div ><div ></div><div ><ul></ul></div></div>');
//Add the control to the card-header element
$(frag).find(".card-header").append('<input type="checkbox" id="checkbox' $("#mainCard.card").length '">' list '');
//Finally append the fragment to the main card
$("#mainCard").append(frag);
});
CodePudding user response:
Consider the following.
$(".add").click(function() {
var list = $("#userInp").val();
var count = $("#mainCard .card").length 1;
count = count > 10 ? count : "0" count;
var card = $("<div>", {
class: "card col-xl-3"
}).appendTo("#mainCard");
$("<div>", {
class: "card-header",
id: "header-" count
}).appendTo(card);
$("<div>", {
class: "card-body"
}).appendTo(card);
$("<ul>").appendTo($(".card-body", card));
$("<button>", {
type: "checkbox",
class: "form-check-input",
id: "checkbox-" count
}).appendTo($(".card-header", card));
});
CodePudding user response:
You can check existing length of the cards like below
$(".add").click(function(){
let cardCount=$("#mainCard.card").length;
let list = $("#userInp").val()
$("#mainCard").append('<div ><div id ="head" (cardCount 1) ></div><div ><ul></ul></div></div>')
$("#mainCard").find("#head" (cardCount 1)).append('<button type = "checkbox" class ="form-check-input" id = "checkbox01"></button>' list '')
})