Home » Jquery » jquery – Why is Javascript alert being called numerous times?-Exceptionshub

jquery – Why is Javascript alert being called numerous times?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment


My example is a prototype sports fantasy page, users select players from a list, and selecting them moves them to another list. Each player has a price, and each user has a salary cap. My problem is that I was trying to implement it so that if a user tried to pick a player they didn’t have the money for, an alert would tell them that. But my problem is that the alert pops up a number of times, such that I press okay and it returns. The number of times it appears also appears random, it doesn’t matter how I click the button.

At first I thought that maybe I was clicking the button a lot but that wasn’t the case. When researching the problem on this page everyone was mentioning adding extra event listeners but I don’t think that is the problem with my code. I have put the code below and tried to remove the unrelated code for easier reading. The js is checking what table the player is in (selected by user or not), checking whether they have the salary and moving the player (I removed the code going the other way because it wasn’t relevant). value is a variable that is the current value of the selected team and stats is a dictionary where the key is the players name linked to a list, where the first index is the price.

My best guess is that maybe the button is getting stuck in the down position, but that doesn’t really make sense?


function myFunction() {
        if ($(this).closest('tbody').attr('id')=='Right') {
            let name = $(this).closest("tr").find("td:first").text();
                alert('You do not have the salary for that')
                $('#lefttable').append('<tr><td>'+name+'</td><td><button onclick="myFunction()" class="btn btn-danger">-</button></td></tr>');


<tbody id="Right">
   {%for player in players%}
     {%if player not in team%}
           <button class="btn btn-danger" onclick="myFunction()">-</button>
How to&Answer: