Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

javascript - jquery clone select element within a <tr><td>

I would like to clone a select and update the name and id values. The select is within a <tr><td>

<table>
<tr id="tr_1">
    <td id="td_1">
        <select name="tech_1" id="tech_1">
            <option value="0">Please Select</option>
            <option value="1">Mango</option>
            <option value="2">Apple</option>
            <option value="3">Banana</option>
            <option value="4">Orange</option>
        </select>
    </td>
</tr>
</table>
<input type="button" id="btnClone" value="Clone" />

I can do it without the table, but my challenge is putting the clone within a new <tr><td> ... </td></tr>

Here is my jquery:

$("#btnClone").bind("click", function () {

   // get the last SELECT which ID starts with ^= "tech_"
   var $tr = $('tr[id^="tr_"]:last');

   // get the last SELECT which ID starts with ^= "tech_"
    var $select = $('select[id^="tech_"]:last');

    // Read the Number from that SELECT's ID (i.e: 3 from "tech_3")
    // And increment that number by 1
    var num = parseInt( $select.prop("id").match(/d+/g), 10 ) +1;

    // Clone it and assign the new ID (i.e: from num 4 to ID "tech_4")
    var $klon = $select.clone().prop('id', 'tech_'+num ).prop('name', 'tech_'+num );

    // Finally insert $klon wherever you want
    $tr.after("<tr><td>").after($klon).after("</td></tr>");
});

This code results in the cloned <select> below the original and nothing between the new <tr><td> and </td></tr>

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add tr and td first with the id of tr and then add select to the td under new tr like following.

$("#btnClone").bind("click", function () {
    var $tr = $('tr[id^="tr_"]:last');
    var $select = $('select[id^="tech_"]:last');

    var num = parseInt($select.prop("id").match(/d+/g), 10) + 1;
    var $klon = $select.clone().prop('id', 'tech_' + num).prop('name', 'tech_' + num);

    $tr.after($("<tr id=tr_" + num + "><td></td></tr>")); // change here
    $('#tr_' + num + ' td').append($klon); // change here 
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...