0

I had guessed that this code would work. But the JS doesn't alert anything. What is the best way to run functions on replaced content? It is a simple code as you can see, if you work with jquery. I need answers only if you have suggestions.

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<button type="button" id="add" name="sub">Add</button> 

<script>
$(document).on('click',"#add",function(){
$( this ).replaceWith("<button type='button' id='sub'> Alert </button>");
});

$(document).ready(function(){
$("#sub").click(function()
{
alert("Does it alert?");
});
});
</script>
J. Doe
  • 63
  • 1
  • 1
  • 12

1 Answers1

0

Add via

$(document).on('click', '#sub', function() { })

Example

$(document).on('click',"#add", function() {
    $( this ).replaceWith("<button type='button' id='sub'> Alert </button>");
});

$(document).ready(function() {
   $(document).on('click', '#sub', function() {
      alert("Does it alert?");
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="add" name="sub">Add</button>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112