Jump to content

loop is not working - clone


felito

Recommended Posts

hi

 

i have this 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/

Link to comment
https://forums.phpfreaks.com/topic/248935-loop-is-not-working-clone/
Share on other sites

it looks like your cloning the valores1 <ol> with the

var newElem = $('#input' + num).clone(true).prop('id', 'input' + newNum);

call.

I think the first argument to clone clones the contents also.

When I change to this:

$(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);

    }

    });

 

the output does not change.

makes sense because the </div> tag is bellow the ol.

 

Anyway, something like:

 

         $('#input' + num).after(newElem);
        $('#valores' + num).after(newElem1);

<div id="input1" class="clonedInput">
</div>
<ol id="valores1">
	<li>lowest</li>
	<li>highest</li>
</ol>

 

 

is not working as expected

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.