简体   繁体   中英

replace the element instead of append

I have the following code where i need to replace the newly created TD column with the new option from the dropdown select. Here is my code

$("#myselction").change(function(e) {
    var neData = $("#myselction").val();
    $("table.data thead tr").append("<th>Idea</th>");
    $("table.data tr:gt(0)").append("<td>" + neData + "</td>");
});

It is appending the data correctly at the end of the table, but everytime i select new option from dropdown, it adds another td column, instead i want to replace it with the one already created and if its new one create it first time.

Alo i am using the following function to add/remove class for odd and even

    zebRaRows('.data tbody tr:odd td', 'odd');
function zebRaRows(selector, className){
  $(selector).removeClass(className).addClass(className);
}

How do i add the above to the dynamically created column

you need to replace append() which append with html() which replace.

try:

$("selector of element to replace").html("<td>" + neData + "</td>");

Here is fiddler for html demo

Your desired behavior is different depending on whether it is the first time the action is occurring or not. In this case, have a boolean flag which records the first time the event occurs. The first time, append the new <td> ; subsequent times, overwrite it.

jsFiddle

var firstTime = true;

$("#myselction").change(function(e) {
    var neData = $("#myselction").val();

    if (firstTime) {
        $("table.data thead tr").append("<th>Idea</th>");
        $("table.data tr:gt(0)").append("<td>" + neData + "</td>");
        firstTime = false;
    }
    else {
        $("table.data tr:gt(0) td:last-child").html(neData);
    }
});

使用.html()创建一个新的。

$("table.data tr:gt(0)").html("<td>" + neData + "</td>");

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