Good day! I’m working on dynamically changing the ID of a button when clicking other buttons. The scenario is as follows:
I have a search button (#searchButton) and three other buttons (#changeButton1, #changeButton2, #changeButton3).
When clicking any of the other buttons (#changeButton1, #changeButton2, or #changeButton3), I want to change the ID of the #searchButton to match the button clicked.
The issue I’m facing is that the ID of the #searchButton changes successfully the first time, but when I click another button (e.g., #changeButton2 or #changeButton3), the ID does not update, even though I can see the change in the Inspect Element (F12). The click handler for the #searchButton doesn’t seem to be triggered after the ID change.
<button id="searchButton" class="btn btn-primary">Search</button>
<button class="btn btn-secondary" id="changeButton1">Button 1</button>
<button class="btn btn-secondary" id="changeButton2">Button 2</button>
<button class="btn btn-secondary" id="changeButton3">Button 3</button>
<script>
$(document).ready(function() {
$('#searchButton').on('click', handleSearchButtonClick);
$('#changeButton1').on('click', function() {
$('#searchButton').attr('id', 'searchButton1');
console.log('ID changed to searchButton1');
});
$('#changeButton2').on('click', function() {
$('#searchButton').attr('id', 'searchButton2');
console.log('ID changed to searchButton2');
});
$('#changeButton3').on('click', function() {
$('#searchButton').attr('id', 'searchButton3');
console.log('ID changed to searchButton3');
});
});
</script>
When I click #changeButton1, the ID of the #searchButton changes to searchButton1. But after that, when I click the other buttons, the ID of #searchButton doesn’t change, and the click event doesn’t seem to fire correctly.
How can I fix this so that the ID can be changed dynamically each time a button is clicked?