Hello everyone,
I’m a bit stuck with the code I’m writing for the bus ride exercise. I’m trying to have the user enter the number of passengers for each station by clicking on three buttons (one for each station). A message will be logged to the console only after the number of passengers for station 3 is typed in the btn3 prompt.
However, the result I’m getting only takes the third button variable value, and not the sum of all three buttons variables values. It seems like this is a scope issue but can’t figure it out.
Can anyone please let me know what I’m missing here?
<h2>Bus ride</h2>
<div id="buttons">
<button id="btnStop1">Station 1</button>
<button id="btnStop2">Station 2</button>
<button id="btnStop3">Station 3</button>
</div>
<script>
$(document).ready(function(){
var station1 = "";
var station2 = "";
var station3 = "";
var btn1 = $("#btnStop1").click(function(){
var station1 = parseInt(prompt("Station 1!, How many passengers go on the bus?"));
if(station1 <= 30) {
console.log(station1);
}else if(station1 > 30) {
console.log("the bus is full! " + (station1 - 30) + " must walk");
}
});
var btn2 = $("#btnStop2").click(function(){
var station2 = parseInt(prompt("Station 2!, How many passengers go on the bus?"));
var stationTwo = station1 + station2;
if(stationTwo <= 30) {
console.log(stationTwo);
}else if(stationTwo > 30) {
console.log("the bus is full! " + (stationTwo - 30) + " must walk");
}
});
var btn3 = $("#btnStop3").click(function(){
var station3 = parseInt(prompt("Station 3!, How many passengers go on the bus?"));
var passgArray = [Number(station1), Number(station2), Number(station3)];
var sum = passgArray.reduce(sumStations);
function sumStations(total, value) {
return total + value;
};
if(sum <= 30) {
console.log(sum + " on the bus, we all go to the last station!");
}else if(sum > 30) {
console.log("the bus is full! " + (sum - 30) + " must walk");
};
});
});
</script>