简体   繁体   中英

How to clone HTML select tag and change its ID in the process?

I am able to change ID's of all other fields except toCity . How can I change its ID when I clone it? With my current code, the dropdown is created with the same data, but the ID remains unchanged.

How can I change the ID when I clone?

 var toAddCloneCount = 1; function AddDestination() { var clone = $("#toAdd").clone(true); clone.find("#days").prop('id', 'days' + toAddCloneCount); clone.find("#toDate").attr('id', 'toDate' + toAddCloneCount); clone.find('#toCity').prop('id', 'toCity' + toAddCloneCount); clone.show(); clone.attr('id', 'toAdd' + toAddCloneCount++).insertAfter("#toAdd"); clone.appendTo("#destinations"); }
 <div id="destinations"> <div id="toAdd"> <table style="width: 100%;"> <tr> <td class="auto-style8">To </td> <td> <select runat="server" id="toCity" name="toCity"></select> </td> <td>Days to Stay</td> <td> <input id="days" type="number" min="1" onkeypress="return false" onkeydown="return false" /> </td> <td> <p> Date: <input id="toDate" type="text" class="getCurrentDate" onkeypress="return false" onkeydown="return false" /> </p> </td> <td> <button type="button" onclick="AddDestination();" >Add+</button> </td> </tr> </table> </div> </div>

var source = document.getElementById('id_here');
var options = source.innerHTML;
var copy = document.createElement("Select"); 
copy.id = "copy_id"
copy.innerHTML = copy.innerHTML + options;
document.body.appendChild(copy);

you can generate new id & name for elements:

$("button").click(function () {
var num = ($("div[id^='cloneItem_']").length + 1);
//alert(num);
$("#cloneItem_1").clone().insertAfter($("div[id^='cloneItem_']").last()).attr("id", 'cloneItem_' + num).find("select").each(function () {

    $(this).prop({
        'id': function (_, id) {
            id = id.substring(0, id.indexOf('_') + 1);
            return id + num;
        },
            'name': function (_, name) {
            name = name.substring(0, name.indexOf('_') + 1);
            return name + num;
        },
            'value': ''
    });

});

});

go to the fiddle demo : clone select element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM