0

Can somebody tell me how to append HTML code that have button element and make that button functional? Why is my function not working on appended button?

Here's my code:

<div id="attachments">
    <input id="add-attachment" type="button" value="Dodaj kolejny &#x271A;" class="button-custom-3">
    <div class="hr-custom-1"></div>
<div>
    <input type="button" value="Przeglądaj" class="button-custom-1">
    <span>Przykładowa nazwa załączonego pliku.jpg</span>
    <input type="button" value="Usuń &#x2716;" class="button-custom-2 button-remove-attachment">
    <div class="hr-custom-1"></div>
</div>

<div>
    <input type="button" value="Przeglądaj" class="button-custom-1">
    <span>Przykładowa nazwa załączonego pliku.jpg</span>
    <input type="button" value="Usuń &#x2716;" class="button-custom-2 button-remove-attachment">
    <div class="hr-custom-1"></div>
</div>

JavaScript functions:

$(".button-remove-attachment").click(function(){
    $(this).parent().remove();
});

$("#add-attachment").click(function(){
    var element = $("<div><input type='button' value='Przeglądaj' class='button-custom-1'><span>Przykładowa nazwa załączonego pliku.jpg</span><input type='button' value='Usuń &#x2716;' class='button-custom-2 button-remove-attachment'><div class='hr-custom-1'></div></div>");
    $("#attachments").append(element);       
});

Please check it on jsFiddle: https://jsfiddle.net/6f9xhr64/

krlzlx
  • 5,752
  • 14
  • 47
  • 55
Kamczatka
  • 151
  • 1
  • 2
  • 15

2 Answers2

0

Since your buttons are added dynamically at some point in time, you have to use On() method overload with three parameters. You should refer to this post: Dynamic Html elements

Community
  • 1
  • 1
Aurimas
  • 145
  • 1
  • 1
  • 7
0

Try using below code

$(document).on("click",".button-remove-attachment",function(){
    $(this).parent().remove();
});


$(document).on("click","#add-attachment",function(){
    var element = $("<div><input type='button' value='Przeglądaj' class='button-custom-1'><span>Przykładowa nazwa załączonego pliku.jpg</span><input type='button' value='Usuń &#x2716;' class='button-custom-2 button-remove-attachment'><div class='hr-custom-1'></div></div>");
    $("#attachments").append(element);

});
Gauri Bhosle
  • 4,985
  • 1
  • 15
  • 19
  • Use above code, all button's functionality are working fine.I have also created jsfiddle for the same .check this link https://jsfiddle.net/btbboahh/1/ – Gauri Bhosle Jan 14 '17 at 19:18