5

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?

1 Answer 1

8

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

2
  • Not sure that works the way i described in my question, based off your example, it clones the items but if you were to type a name into the text field then press clone it doesn't clone that individual name. for example try the following. type into the text field tom > press clone steve > press clone etc
    – NewBoy
    Dec 22, 2015 at 16:45
  • See my updated answer. That has a working sample as well.
    – Shyju
    Dec 22, 2015 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.