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?
CodePudding user response:
- The reason you code did not work is because what happen is while code execute
$('#btnSendInvoice').click(function() {line it will find element withidasbtnSendInvoiceand assign event & itsfunctionto that element. At the beginning you have buttonwithidbtnSendInvoice` so it will assign that function to it. - On next line it executes
$('#btnSetPayment').click(function() {, so it will find element withidasbtnSetPaymentbut at that moment there won't be any such element so this event will not be assigned to any element. - Later when you click on
Button Ayou change itsidbut event is bind withelementitself so event won't be changed and it will continue triggering same old function.
Solution 1
- Update your existing
$('#btnSendInvoice').click(function() {function and add conditional code using conditions likeif ($(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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Solution 2
- You can use
delegatebinding using$(document).on("click", "#btnSendInvoice". Using this it will bind event todocumentand on click it will try to finddelegate eventusingidof current element or any other validselectors. 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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
