0

I am using NodeJS and Socket.IO and I encountered this problem with JQuery on front-end. I do not get any error, but when I run the for loop JQuery registers all the clicks as if it was one button. (For example, when you click the Add Flour button it adds bread).

CodePen: https://codepen.io/anon/pen/qXbbQg

Javascript:

var stocks = [ ["flour", 0], ["bread", 0] ];
var getNumInput = function(id){
    return Number(document.getElementById(id).value);
};
window.onload = function() {
  var socket = io(); // Server will see this as connection

  for(x in stocks) {
    $("#" + stocks[x][0] + "Remove").click(function(){
        stocks[x][1] = stocks[x][1] - getNumInput(stocks[x][0] + "In");
            socket.emit('stocksUpdate', stocks);
    });
    $("#" + stocks[x][0] + "Add").click(function(){
        stocks[x][1] = stocks[x][1] + getNumInput(stocks[x][0] + "In");
        socket.emit('stocksUpdate', stocks);
    });
  }

HTML:

<h1 id="flour">Waiting for connection to server</h1>
<form action="">
    <button type="button" name="button" style="width: 100px; height: 30px;" id="flourRemove">Remove</button>
    <input type="number" name="flourIn" value="10" id="flourIn">
    <button type="button" name="button" style="width: 100px; height: 30px;" id="flourAdd">Add</button>
</form>
<h1 id="bread">Waiting for connection to server</h1>
<form action="">
    <button type="button" name="button" style="width: 100px; height: 30px;" id="breadRemove">Remove</button>
    <input type="number" name="breadIn" value="10" id="breadIn">
    <button type="button" name="button" style="width: 100px; height: 30px;" id="breadAdd">Add</button>
</form>

All I am doing on server-side is emit-ing the information I got so all users can see it, so don't worry about the socket code.

  • The value of `x` when your callback occurs is not what it was when the callback was created. See the linked question's answers for details. – T.J. Crowder Jul 29 '17 at 13:05
  • @T.J.Crowder So could I just do (array).forEach(function(arrayElement){..,});? –  Jul 29 '17 at 13:15
  • That's one of the approaches you can use, absolutely: `stocks.forEach(function(x) { /*...*/});` would work (`x` wouldn't change). Side note: Don't use `for-in` to loop through arrays in any case. [See this answer](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476) for how to loop through arrays. – T.J. Crowder Jul 29 '17 at 13:19

0 Answers0