I have been trying to take values of 4 inputs that are in a table and get the sum of the numbers on the input with a for loop but i keep getting 0 (the sum that i have defined)
Debugged everything and I am pretty sure the problem is in the "var x"- it just won't get any information from the inputs.
$(function () {
$("#inventoryForm").submit(function (event) {
var table = $("table")
var error = false;
event.preventDefault();
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
error = true; //Indicate there was an error
$("#inventoryError").slideDown().text("Positive numbers only");
return false; //This stops the iteration
}
});
//Stop processing if there was an error
if (error) return;
if (!error) {
$("#inventoryError").hide();
}
$("#inventorySubmit").hide();
$("#inventoryChange").show();
$("#withdraw").show();
$(".inventoryInput").attr('disabled','disabled');
var sum = 0;
var money = table.find("td:nth-child(2)");
for (var i = 0; i<money.length; i++) {
var x = money.eq(i).val();
sum += x;
$("#totalMoney").text(sum);
}
console.log(money);
});
$("#inventoryChange").click(function () {
$("#inventorySubmit").show();
$("#inventoryChange").hide();
$("#withdraw").hide();
$(".inventoryInput").removeAttr('disabled');
});
});
.hidden {
display: none;
}
.error {
display: none;
color: red;
border: dotted 3px yellow;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>ATM</title>
<body>
<header>
<h1>Litman - Steklov ATMs</h1>
</header>
<section id="inventory">
<form id="inventoryForm">
<table>
<thead>
<tr>
<th>Bill</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>
<input id="inventoryInput" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>50</td>
<td>
<input id="inventoryInput2" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>100</td>
<td>
<input id="inventoryInput3" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>200</td>
<td>
<input id="inventoryInput4" class="inventoryInput" type="number">
</td>
</tr>
</tbody>
</table>
<p id="inventoryError" class="error hidden">Validation errors will be here</p>
<p>Total Money: <span id="totalMoney"></span>
</p>
<button id="inventorySubmit" type="submit">Finish</button>
<button id="inventoryChange" type="button" class="hidden">Change</button>
</form>
</section>
<section id="withdraw" class="hidden">
<form>
<div>Withdraw:
<input type="number">
</div>
<p class="error hidden">Validation errors will be here</p>
<button type="submit">Process</button>
</form>
</section>
<section id="result" class="hidden">
<div>You Got:</div>
<button type="button">Finish</button>
</section>
</body>
</html>
java. And if you want to make sure where the problem is, debug. Log something inside the loop.x. I'm not saying this will solve your problem but it will give you more information.