SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2010
    Posts
    63
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    loop is not working - clone

    hi

    i have this code

    Code: [Select]

    Code:
    <script type="text/javascript">
    $(document).ready(function() {
    	for ($i=0; $i<4; $i++) {
            var num = $('.clonedInput').length;
            
            var newNum = new Number(num + 1);
            
            var newElem = $('#input' + num).clone(true).prop('id', 'input' + newNum);
            var newElem1 = $('#valores' + num).clone(true).prop('id', 'valores' + newNum);
            
    
            $('#input' + num).after(newElem);
            $('#valores' + num).insertAfter(newElem1);
    
        }
    
        });
    </script>
    
    <div id="input1" class="clonedInput">
    	<ol id="valores1">
    		<li>lowest</li>
    		<li>highest</li>
    	</ol>
    <input readonly id="sliderProgInput" size="20"  name="myformdata[valor][]"/>
    </div>
    the input id is changed correctly, but valores no. Why ?? Valores is always id="valores1", and must be id="valores1", id="valores2", and so on.

    demo
    http://jsfiddle.net/Gpugn/

  2. #2
    SitePoint Enthusiast Anthony.Barnes's Avatar
    Join Date
    Aug 2011
    Location
    Canberra, Australia
    Posts
    80
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I find recursive functions much easier to handle this kind of loop. The problem here was the clone of '#input' + num was also cloning the '#valores' list, so your clone wasn't actually working.

    Here is an example of using a recursive function to clone the inputs:
    http://jsfiddle.net/Gpugn/18/

    You might also want to increment the numbering used for #sliderProgInput since that input is also cloned in the process and keeps the same id for each cloned element.

  3. #3
    SitePoint Enthusiast
    Join Date
    Sep 2010
    Posts
    63
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    wow man, you are a javascript guru.

    thanks


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •