Home › Forums › JavaScript › .clone problem
- This topic is empty.
-
AuthorPosts
-
May 6, 2014 at 2:27 am #169307
alpkank
ParticipantI have a drop-down menu and a button to run a simple function. I added a clone button to duplicate the section. However when I hit the clone button, drop-down menu and button stop working. I looked online (https://api.jquery.com/each/) for a solution but it still not working even though I added .clone(true);
I would appreciate if someone can tell me what is wrong with the code. Thank you.<input id="butt" type="button" value="Clone" /> <div id="container"> <form name="Form1" action="#" method="post" id="formid"> <select class="select1" id="selectid" name="selectuser" onChange='Choice();'> <option>Your text</option> <option value="1">English</option> </select> <input class="input1" type="text" id="ids" name="id"> <input type="button" value="Submit" name="B1" onclick="getText()"> </form> </div> <div id="cloned"></div> <script language="JavaScript"> function getText() { var myString=document.Form1.ids.value; var list3 = myString.split('') var list1 = ["1", "2", "3", "4", "5", "6"]; var list2 = ['a', 'b', 'c', 'o', 'h']; for (var i = 0; i < list3.length; i++) { if(list1.indexOf(list3[i]) >= 0){ alert("number"); } else if(list2.indexOf(list3[i]) >= 0){ alert("letter"); } else{ alert("not a number and not a letter"); } } } </script> <script> var ids = new Array(); ids[0] = ""; ids[1] = "h2o"; function Choice() { y = document.getElementById("selectid"); document.getElementById("ids").value = ids[y.selectedIndex]; } </script> <script> $('#butt').click(function(){ var $orginal = $('#container'); var $cloned = $orginal.clone(true); $cloned.find('textarea').each(function(index, item) { //set new textareas to value of old textareas $(item).val($originalTextareas.eq(index).val()); }); $cloned.appendTo('#cloned'); }); </script>
May 7, 2014 at 3:01 am #169423Chromawoods
ParticipantAlthough I don’t know for sure what’s wrong, there is a problem in your code, namely the ID attributes on the elements that you clone. You will end up with duplicates, which is invalid. Use classes or data-attributes instead.
Is there perhaps a live example of the problem? A CodePen?
May 7, 2014 at 3:31 am #169424alisnikol
ParticipantTry this,
code the clone by hand properties after properties and check that mutable instances are cloned too.
pro:
– control of what will be performed
– quick execution
cons:
– tedious to write and maintain
– bug prone (copy/paste failure, missing property, reassigned mutable property)Use reflection:
With your own reflection tools or with an external helper (like jakarta common-beans) it is easy to write a generic copy method that will do the job in one line.
pro:
– easy to write
– no maintenance
cons:
– less control of what happens
– bug prone with mutable object if the reflection tool does not clone sub objects too
– slower execution -
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.