Aaron Aaron - 2 months ago 6
jQuery Question

JQuery removing buttons dynamically

I am adding buttons based on an array. The problem I am having is that every time I add another name to the array, it prints out all the buttons not just the one I added. I am wondering how would I erase all the old buttons before I add the array of buttons.

Here is my code

socket.on('usernames', function(data){
console.log(data);
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
// $users.html(html);
});


Below is an image. Test is the name of the first button and every time I add a new button it prints the entire array again. Is there a way to delete the old buttons?
enter image description here

Answer

Use the empty() method before you loop:

socket.on('usernames', function(data){
    var $contentWrap = $("#contentWrap").empty();

    for (i = 0; i < data.length; i++) {
        $input = $('<input type="button"/></br>');
        $input.val(data[i]);
        $input.appendTo($contentWrap);
    }
});

Also note that you can improve performance and tidy the code by creating a single HTML string and setting the html() property to only require one DOM call. Try this:

socket.on('usernames', function(data){
    var html = data.map(function(value) {
        return '<input type="button" value="' + value + '"/></br>'
    }).join('');
    $('#contentWrap').html(html);
});
Comments