javascript/jquery clone not working in dropdown list

巧了我就是萌 提交于 2019-12-13 04:38:54

问题


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/


回答1:


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.




回答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())
        })
    }
});


来源:https://stackoverflow.com/questions/17274081/javascript-jquery-clone-not-working-in-dropdown-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!