Reputation: 95
I am currently doing a computer science project, where I am trying to create a calculator for a points system, the type of transport provides a multiplier where the distance is used to calculate it. At first I had the the distance at a set number of 10, however when I tried to change it to where the user inputs a distance, the number calculated is not considered a number. My code is below:
var Companies = [
[1, "Barclays", 50, 100],
[2, "Google", 20, 40],
[3, "Microsoft", 80, 160]
];
var Transport = [
["Car", 1.2],
["Bike", 1.5],
["Walk", 1.6],
["Public Transport", 1.3],
["Car Share", 1.4]
];
var Distance = 10;
var Carbo = 0;
function Carbo_Calculator() {
var Transport_Chosen = document.getElementById("Transport_Chosen").value;
var Company_Chosen = document.getElementById("Company_Chosen").value;
for (i = 0; i < Transport.length; i++) {
if (Transport_Chosen == Transport[i][0]) {
Carbo = Distance * Transport[i][1];
for (j = 0; j < Companies.length; j++) {
if (Company_Chosen == Companies[j][1]) {
Companies[j][3] = Companies[j][3] + Carbo;
console.log(Companies);
}
}
alert(Carbo);
}
}
}
<h1>Transport:</h1>
<select id="Transport_Chosen">
<option>Transport...</option>
<option value="Car"> Car </option>
<option value="Bike"> Bike </option>
<option value="Walk"> Walk </option>
<option value="Public Transport"> Public Transport </option>
<option value="Car Share"> Car Share </option>
</select>
<h1>Companies:</h1>
<select id="Company_Chosen">
<option>Companies...</option>
<option value="Barclays"> Barclays </option>
<option value="Google"> Google </option>
<option value="Microsoft"> Microsoft </option>
</select>
<h1>Distance</h1>
<input type="number" id="Distance" placeholder="Distance">
<button onclick="Carbo_Calculator()"> Go! </button>
Even though the distance is set to 10, when I change it to Distance = document.getElementById("Distance).value;
and then try to run it, where the user inputs it, the alert says not a number, even though the data type input is a number.
Upvotes: 0
Views: 81
Reputation: 674
from isNAN
function we can identify variable is numeric or not.
If type cast is string for ex- "100"
then we can parse it to number (integer or float)
parseInt() OR parseFloat()
Upvotes: 1
Reputation: 67505
You need to parse your data to numbers since the .value
attribute returns a string, so when you enter 10 for example the input.value
will return a string "10"
.
You could use Number()
or parseInt()
like :
var Transport_Chosen = Number( document.getElementById("Transport_Chosen").value );
var Company_Chosen = Number( document.getElementById("Company_Chosen").value );
//Or
var Transport_Chosen = parseInt( document.getElementById("Transport_Chosen").value );
var Company_Chosen = parseInt( document.getElementById("Company_Chosen").value );
Upvotes: 1