This time I tried to make a code which lets user choose the location where he/she wants to go. I've wrote html and js but now I've been stuck (about half a day...) by connecting them. I have written a dropdown menu with help of bootstrap. I have also written a js file which should loop those locations. Finally it should understand what user has choosen and then output the result which should be:
var text = '<p>' + buses[i].to + '<br> - Distance from Estonia: ' + buses[i].distance + ' km <br> - Price: ' + buses[i].price + ' euros <br>'
In web browser something like this:
Amsterdam
- Distance from Estonia: 2000 km
- Price: 250 euros
But whatever I try, nothing works (I know it's because of my poor knowledge, i don't blame JS). I have tried to put "id" and "onclick function" everywhere.
So, I'll paste a little part of it, maybe someone could help :)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<h2>Buses</h2>
<p id="test1">...</p>
<p id="test2">...</p>
<script src="js/buses.js"></script>
<!-- Dropdown menu for beautiful usage -->
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" id="dropdownMenu2" type="button">
List of locations
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenu2">
<ul id="boss">
<li><a role="button" onclick="bus()" value="Amsterdam">">Amsterdam</a></li>
<li><a role="button" onclick="bus()" value="Madrid">Madrid</a></li>
<li><a role="button" onclick="bus()" value="Stockholm">Stockholm</a></li>
<li><a role="button" onclick="bus()" value="Riga">Riga</a></li>
</ul>
</div>
</div>
</body>
</html>
And my JS file:
// If person is in some location
document.getElementById("test2").innerHTML = "<hr> You're in Estonia, where would You want to travel?";
function bus() {
// Object with info
var buses = [
{ to: 'Amsterdam', distance: 2000, price: 250},
{ to: 'Madrid', distance: 4500, price: 350},
{ to: 'Stockholm', distance: 1500, price: 90},
{ to: 'Riga', distance: 400, price: 100}
];
// Should get result which user has choosen
var res = document.getElementById("boss");
var result = res.value;
console.log(value); // outputs html row... >.>
// Loop through the object
var text = "";
for(var i = 0; i < (buses.length); i++) {
if (result == buses[i].to) { text = '<p>' + buses[i].to + '<br> - Distance from Estonia: ' + buses[i].distance + ' km <br> - Price: ' + buses[i].price + ' euros <br>';
alert("Works!!!!"); // Well, last thing is to change it to output "var text" result
}
};
document.getElementById("test2").innerHTML = text; // If everything is correct, this should output sentence about selected bus
}
Thanks!