I have created a clone function to clone a selection of elements. I have managed to get the basics of the clone function working. CLICK HERE I have a bug in this function. When the user types text into the input field, it clones the last inputted text and changes the text value for all cloned items.
$('.add-item').on('click', function() {
var value = $('input').val();
if ($('#items-field').val()) {
$('.list-items p').text(value)
$('.list-items:first').clone().appendTo("#items").addClass('isVisible');
$('input').val('');
event.preventDefault();
}
})
Does anyone know how this problem can be resolved?
jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.
clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.
To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.
You call the cloneNode() method on the element you want to copy. If you want to also copy elements nested inside it, pass in true as an argument. // Get the element var elem = document. querySelector('#elem1'); // Create a copy of it var clone = elem.
Clear the value of inputs after you clone()
. You can use the find()
method to get all the inputs inside the cloned item.
var c = $('.list-items:first').clone();
c.find("input").val(""); // find all inputs and clear
c.appendTo("#items").addClass('isVisible');
Here is a working jsbin sample
Also, In your code, you are reading the input value and setting it to all the p
tags's text. You should be setting it only to the p tag of the cloned div.
$(function(){
$('.add-item').on('click', function(e) {
event.preventDefault();
var value = $('#items-field').val();
if (value!="") {
var c = $('.list-items:first').clone();
c.find("input").val(""); // find all inputs and clear
c.appendTo("#items").addClass('isVisible');
c.find("p").text(value);
}
});
})
Here is a working sample of the complete solution
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With