I initially got this code and all works well:
<div class="rm">
<button id="sub" type="submit">
<span>Registo</span>
</button>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(".rm>#sub").click(function(event) {
event.preventDefault();
var formdata = $("#custom").serialize();
$.ajax({
url: "dojo/insert.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data) {
switch (data.livre) {
case 'error':
$(".rm").html('<button id="sub" type="submit"><span>Rever</span></button>');
break;
default:
$('#paginas').delay(50).load('profile_empresa_3.php');
break;
}
}
});
return false;
});
});
</script>
The problem now. When i add $(".rm").html("") with a button with the same id. If i click in this new button the page is reloaded. My question is. If the button added has the same id, why the click handler is not repeated ?
thanks
At the time you bind the event handler to
$(".rm > #sub"), the new element does not exist yet, so jQuery cannot bind the handler to it.You could either rebind the event handler, or bind it to
$('.rm')instead and use event delegation (using.on()) :But instead of replacing the whole element, it seems you could just change its text content:
Also note that IDs are supposed to be unique, having two elements in the DOM with the same ID is invalid.