0

I asked a question in the last post that i want rows to be dynamically generated and the data should be copied in the new row. it is working fine but only for text fields. but i also have dropdown in my form and it isn't showing the last row's selected options in new row. this was my question add previous row data to dynamically generated row

i have html code :

<form>
    <table border="1" id="engagements">
        <tr>
            <th>
                <input type="checkbox" onclick="checkAll(this)" />
            </th>
            <th>Organization</th>
            <th>Project</th>
            <th>Product</th>
            <th>Activity</th>
        </tr>
        <tr>
            <td>
                <input type="checkbox" onclick="checkAll(this)" />
            </td>
            <td>
                <select>
                    <option value = "1">One</option>/>
                     <option value = "1">two</option>/>
            </td>
            <td>
                <input type="text" />
            </td>
            <td>
                <input type="text" />
            </td>
            <td>
                <input type="text" />
            </td>
        </tr>
    </table>
    <select name="mode" id="mode">
        <option value="">Add More Rows with Same Data as Above</option>
        <option value="1">1 More</option>
        <option value="2">2 More</option>
        <option value="3">3 More</option>
        <option value="4">4 More</option>
        <option value="5">5 More</option>
    </select>
</form>

and script code :

$("#mode").on('change', function () {
    var rows = parseInt(this.value);
    console.log(rows);
    var lastRow;
    for (var i = 0; i < rows; i++) {
        lastRow = $('#engagements tr').last().clone();
        $('#engagements tr').last().after(lastRow);
    }
});

JS fiddle: http://jsfiddle.net/jW6eL/3/

Community
  • 1
  • 1
Shauzab Ali Rawjani
  • 256
  • 1
  • 4
  • 16

2 Answers2

3

for performance reasons, jquery doesn't keep selection while making clone of an element. However, you can try using

    .clone(true) 

this will copy all evens and data with drop down. this way you may use events and and select last option in the drop down.

animuson
  • 53,861
  • 28
  • 137
  • 147
imonweb
  • 31
  • 2
2

try this

http://jsfiddle.net/jW6eL/7/

$("#mode").on('change', function () {
    var rows = parseInt(this.value);
    console.log(rows);
    var lastRow;
    for (var i = 0; i < rows; i++) {
        lastRow = $('#engagements tr').last().html();
        $('#engagements tr:last').after('<tr>'+lastRow+'</tr>');
        $('#engagements tr:last').find('select').each(function(){
            var this_select=$(this);
            this_select.val(this_select.closest('tr').prev().find('td:eq('+this_select.closest('td').index()+')').find('select').val())
        })
    }
});
sangram parmar
  • 8,462
  • 2
  • 23
  • 47