2

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>

5
  • You don't mean java. And if you want to make sure where the problem is, debug. Log something inside the loop. Commented May 24, 2015 at 11:03
  • Please edit your question and show your HTML Commented May 24, 2015 at 11:05
  • @rnevius you can see my HTML on my fiddle above. Commented May 24, 2015 at 11:06
  • @keyser , I was trying to log "x" and I got nothing- so somehow I don't get any value from the input. Commented May 24, 2015 at 11:07
  • @ronilitman Then you have an obvious follow-up: log the parts that make up x. I'm not saying this will solve your problem but it will give you more information. Commented May 24, 2015 at 11:08

1 Answer 1

2

The problem is indeed with

var x = money.eq(i).val();

money is an array of tds. So money.eq(i) is a td. What you want to get to is the actual input. So the solution is

var x = money.eq(i).find('input').val();

To elaborate on your further commend. If you fill in all 4 inputs using

var x = parseInt(money.eq(i).find('input').val());

it will sum them as expected. It will throw NaN when one of the inputs is empty because parseInt('') returns NaN, so you should check if the input actually has a value or not..

var input = money.eq(i).find('input').val();
var x = input ? parseInt(input) : 0

To further explain my code.

var input = money.eq(i).find('input').val();

This gets the value of the actual input, whatever that value may be.

var x = input ? parseInt(input) : 0

This checks whether the value of the input is empty or not. If it is empty then x=0 otherwise x=parseInt(input). So if the input is not empty, the value if being parsed to an int and assigned to x.

sum += x

x is being added to the final sum.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, it worked. For now, I just getting the numbers like strings. for exmaple- if I entered "2" on the first input and "1" on the second the result will be "021". Tried to correct it with parseInt but got "NaN" as a result. Do you know how can I fix it? My input is defined of a "number" type.
Edited my answer to include fix for that.
It worked. I just don't get it- If I do sum += x but I defined my input values with "var input", how does it know to relate it?
Further edited my answer and explained each line of code
Glad to help, my friend
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.