I'm trying to make simple app and I have the following idea. I have two input fields in which user can choose city and I also have JSON from which I want to get results. Now what I want is that the depending on which cities user chooses he gets different result. This is my Object(JSON):
var cities = {
"newyork": {
"newyork": 0,
"washington": 50,
"sacramento": 100,
"miami": 150
},
"washington": {
"washington": 0,
"newyork": 50,
"sacramento": 100,
"miami": 150
}
};
This is my HTML:
<form>
<select id="firstInput" onchange="calculatePrice()">
<option value="newyork">newyork</option>
<option value="washington">washington</option>
<option value="sacramento">sacramento</option>
<option value="miami">miami</option>
</select>
<select id="secondInput" onchange="calculatePrice()">
<option value="newyork">newyork</option>
<option value="washington">washington</option>
<option value="sacramento">sacramento</option>
<option value="miami">miami</option>
</select>
</form>
<div id="output">Output: 500</div>
Example of the thing I want to achieve: User chooses New York in first input and Sacramento in second. Output changes to 50. As you can see I want to load data from my JSON or object in JS.
This is my JS:
function calculatePrice() {
var x = document.getElementById("firstInput").value;
console.log(x);
var y = document.getElementById("secondInput").value;
console.log(y);
console.log(cities.x.y);
document.getElementById("output").innerHTML = "Output: " + cities.x.y;
}
But using this code I get the following error:
Uncaught TypeError: Cannot read property 'y' of undefined
This is confusing because when I console.log(y) it seems to be working fine.
Can anyone help me with this ?
Here is JSBin so you can have a better look:
https://jsbin.com/laluzawuda/edit?html,js,console,output