Karem
Karem

Reputation: 18103

jQuery Copy and append tr's as many as selecting

HTML:

<table id="mytable">
<tr>
    <td>
        <select name="antal_tidspunkter" id="antal_tidspunkter">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
        </select>
    </td>
</tr>
<!-- These three <tr>s below should be duplicated to under each other -->
<tr>
    <td>This should be duplicated</td>
</tr>
<tr>
    <td>This too</td>
</tr>
<tr>
    <td>Hey, me too!</td>
</tr>
<!-- Above should be duplicated as of many you select in the select -->
</table>

JavaScript:

$(document).ready(function(){
    $('#antal_tidspunkter').change(function(){
        //
    });
});​

Here's the sample: http://jsfiddle.net/PMXmY

I would like to do so when you change the selector to 2 it should appear a duplicate of the current 3 tr's, so total 6 tr's..

I have wrote the jquery change() handler for the selector, but how can I do so it duplicates the three tr's and append them under.

So when you have chosen 3, it should appear total 9 <tr>'s, like this: http://jsfiddle.net/PMXmY/2/ (this is not working I have just manually duplicated the tr's in the html)

Upvotes: 0

Views: 96

Answers (2)

VisioN
VisioN

Reputation: 145428

How about this solution?

$("#antal_tidspunkter").on("change", function() {
    $("#mytable tr:gt(3)").remove();
    for (var i = 1; i < this.value; i++) {
        $("#mytable tr:not(:first):lt(3)").clone().appendTo("#mytable");
    }
});​

If you don't need to remove the cloned rows every change time, just delete the second line.

DEMO: http://jsfiddle.net/PMXmY/16/

Upvotes: 1

Ayush
Ayush

Reputation: 42450

$(document).ready(function(){
    $('#antal_tidspunkter').change(function(){
        // get the number selected and subtract one to 
        // get the number of clones you need to append
        var num = parseInt($(this).val()) - 1;
        
        // the target to which the items will be appended
        var target = $('#mytable');

        //loop that will run as many times as the number that was selected
        for(i =0; i < num; i++) {
            //loop to clone and append only the first three tr's
            for(j = 1; j <=3; j++) {                
                // find the tr, clone it and append it to the target
                target.find('tr').eq(j).clone().appendTo(target);

            }
        }
    });
});​

Demo

Commented the code so you can understand it.

Upvotes: 0

Related Questions