Question

var select;
window.onload = function () {
var select = document.getElementById("money");
console.log(select);
}

function changedepositedInput(objDropDown) {
console.log(parseInt(objDropDown));
var objdeposited = document.getElementById("deposited");
objdeposited.value=parseInt(objdeposited.value);
var total=parseInt(objdeposited.value);
objdeposited.value = parseInt(objDropDown.value+total);
objdeposited.value = parseInt(objdeposited.value);
}
</script>
<h1>Vending Machine Project</h1>
<form name="vendingmachine" action=" ">
Choose Bevrage<br>
        <input name="item" type="radio" value="water" checked="checked">Water 75 cents<br>
        <input name="item" type="radio" value="soda">Soda $1.50<br>
        <input name="item" type="radio" value="coffee">Coffee $1.00<br>
        <input name="item" type="radio" value="beer">Beer $2.00<br>
<p>
    <label>Deposit Money:
        <select name="money" id="money" onchange="changedepositedInput(this)">
            <option>Choose Amount</option>
            <option value="10">10 cents</option>
            <option value="25">25 cents</option>
            <option value="50">50 cents</option>
            <option value="75">75 cents</option>
            <option value="100">$1.00</option>
        </select>
    </label>
</p>
<p>Total Deposited:<input name="deposited" id="deposited" type="text" readonly="TRUE" value=" "></p>

using this code I am not getting a return of a solid number, for example in a drop down menu I would select two values ie 50 and 75 and they would combine as 5075, does this mean it is still running it through as string somewhere and if so where?

Était-ce utile?

La solution

for example in a drop down menu I would select two values ie 50 and 75 and they would combine as 5075, does this mean it is still running it through as string somewhere and if so where?

Yes, here:

objdeposited.value = parseInt(objDropDown.value+total);

objDropDown.value is a string, e.g. '50', and total is a number, e.g. 75.

In JavaScript, '50'+75 is '5075'.

You can replace these 3 lines

var total=parseInt(objdeposited.value);
objdeposited.value = parseInt(objDropDown.value+total);
objdeposited.value = parseInt(objdeposited.value);

with

var total = parseInt(objdeposited.value);
objdeposited.value = parseInt(objDropDown.value||'0') + total;

Edit:

The default value for the deposited value was a space " " which was causing problems. Change this to the empty string "". Also add a ||'0' to all calls to parseInt (or parseFloat). See http://jsfiddle.net/es2yS/1/ .

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top