Adding a button dynamically with JQuery without using .append

97 views Asked by At

I've got a scenario in which I want a button to appear, however this scenario is looped over.

My code at the moment looks like:

var r = $('<input type="button" value="Done swapping"/>');
$('#doneSwapping').append(r);

I only want the button to appear once, but due to using .append it keeps getting added during each iteration, resulting in several buttons.

Is there a way around this? Maybe removing the button again at the end of the loop? I did try .remove but that seems to remove the entire 'doneSwapping' reference rather than just the button.

Thank you :)

2

There are 2 answers

0
ozil On BEST ANSWER

you need to use .empty() it will not destroy the structure but the content in side it.

$('#doneSwapping').empty();  

.remove() will destroy the container.

0
Adil On

First of all try to move it outside loop. If you can not dot hat then before adding check if it is already added. You can use some attribute of button like I used class

var r = $('<input type="button" value="Done swapping" class="cls"/>');
if($('#doneSwapping .cls').length == 0)
    $('#doneSwapping').append(r);