valkyrd valkyrd - 4 months ago 10
jQuery Question

jQuery's click() inside "for" loop firing once

This is my HTML code:

<!DOCTYPE html>
<head>
<title>Chemist</title>
<link href="stylesheet.css" rel="stylesheet">
</head>
<body>
<h2 id="money"></h2>
<table border="1px" id="inventory_t"></table>
<script src="jquery.js"></script>
<script src="app.js"></script>
</body>
</html>


This is the app.js code:

var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;

updateMoney();
populateInventory();
checkAddToMixClick();

function updateMoney(){
$("#money").text(money + "$");
}
function populateInventory(){
$("#inventory_t").empty();
$("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
for(let i = 0; i < inventoryLength; i++){
$("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td id='add_to_mix_" + i + "'>+</td></tr>")
}
}
function checkAddToMixClick(){
for(let i = 0; i < inventoryLength; i++){
$("#add_to_mix_" + i).click(function(){
inventoryAmounts[i]--;
populateInventory();
});
}
}


My problem is that when I run this and click the "+" the click() event fires, but after that nothing happens.

Debugging shows that when I call the checkAddToMixClick() function and click the "+" it works again, but stops working after that.

Any solution this?

Answer

Just add checkAddToMixClick(); to your populateInventory() function, and remove checkAddToMixClick() from the top of your code.

var money = 10;
var inventoryNames = ["Carbon", "Hydrogen"];
var inventoryAmounts = [5, 5];
var inventoryLength = 2;

updateMoney();
populateInventory();

function updateMoney(){
    $("#money").text(money + "$");
}
function populateInventory(){
    $("#inventory_t").empty();
    $("#inventory_t").append("<tr><td colspan='3'>Inventory</td></tr>")
    for(let i = 0; i < inventoryLength; i++){
        $("#inventory_t").append("<tr><td style='text-align:center'>" + inventoryNames[i] + "</td><td style='text-align:center'>" + inventoryAmounts[i] + "</td><td id='add_to_mix_" + i + "'>+</td></tr>")
    }
    checkAddToMixClick();
}
function checkAddToMixClick(){
    for(let i = 0; i < inventoryLength; i++){
        $("#add_to_mix_" + i).click(function(){
            inventoryAmounts[i]--;
            populateInventory();
        });
    }
}
<!DOCTYPE html>
<head>
    <title>Chemist</title>
    <link href="stylesheet.css" rel="stylesheet">
</head>
<body>
    <h2 id="money"></h2>
    <table border="1px" id="inventory_t"></table>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
</body>
</html>