Reputation: 4268
this is my situation:
<button id="btnSendInvoice">Button A</button>
// Btn Send Invoice
$('#btnSendInvoice').click(function() {
console.log(BUTTON A)
$("#btnSendInvoice").text("Button B")
$("#btnSendInvoice").attr("id","btnSetPayment")
});
// Btn Set Payment
$('#btnSetPayment').click(function() {
console.log(BUTTON B)
});
Optical it works. If I pressed Button A, I get in console "Button A" and the button text changed to Button B, also the ID to btnSetPayment.
If I press now the "new" Button B, I get Button A in console again. Where is my mistake?
Upvotes: 0
Views: 96
Reputation: 12629
$('#btnSendInvoice').click(function() {
line it will find element with id
as btnSendInvoice
and assign event & its function
to that element. At the beginning you have buttonwith
id
btnSendInvoice` so it will assign that function to it.$('#btnSetPayment').click(function() {
, so it will find element with id
as btnSetPayment
but at that moment there won't be any such element so this event will not be assigned to any element.Button A
you change its id
but event is bind with element
itself so event won't be changed and it will continue triggering same old function.Solution 1
$('#btnSendInvoice').click(function() {
function and add conditional code using conditions like if ($(this).attr("id") == "btnSendInvoice") {
& if ($(this).attr("id") == "btnSetPayment") {
. Complete code is as below.// Btn Send Invoice
$('#btnSendInvoice').click(function() {
if ($(this).attr("id") == "btnSendInvoice") {
console.log("BUTTON A")
$("#btnSendInvoice").text("Button B")
$("#btnSendInvoice").attr("id", "btnSetPayment")
} else if ($(this).attr("id") == "btnSetPayment") {
console.log("BUTTON B")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<button id="btnSendInvoice">Button A</button>
Solution 2
delegate
binding using $(document).on("click", "#btnSendInvoice"
. Using this it will bind event to document
and on click it will try to find delegate event
using id
of current element or any other valid selectors
. So it will work. Try like below.P.S. Delegate
events may impact on performance.
$(document).on("click", "#btnSendInvoice", function() {
console.log("BUTTON A")
$("#btnSendInvoice").text("Button B")
$("#btnSendInvoice").attr("id", "btnSetPayment")
});
// Btn Set Payment
$(document).on("click", "#btnSetPayment", function() {
console.log("BUTTON B")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<button id="btnSendInvoice">Button A</button>
Upvotes: 1