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.