Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery clone() input value function

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?

like image 976
NewBoy Avatar asked Dec 22 '15 16:12

NewBoy


People also ask

What is Clone function in jQuery?

jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.

When using clone () which attribute can create conflict?

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.

How do you clone an object in jQuery?

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.

How do I copy an element in Javascript?

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.


1 Answers

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

like image 154
Shyju Avatar answered Oct 24 '22 04:10

Shyju