Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am creating an seat booking page with html/javascript.

This is part of the criteria I am working on:

  • When Passengers 1 to 4, Add £0.10 to Fare per mile

  • When number of miles is less than or equal to 10, then Fare per mile is £1.-

The problem is, is that when I try to add together the total cost + cost for passengers, it concatenates the variable (tried it both ways).

Any help would be greatly appreciated.

function MyFunction() {
  var x, text, passengers, passengerresponse, cost;

  miles = document.getElementById("miles").value;
  
  if (isNaN(miles) || miles < 1) {
    text = "Input not valid";
  } else if (miles <= 10) {
    cost = miles;
  }
  
  document.getElementById("miles2").innerHTML = miles;

  passengers = document.getElementById("passengers").value;

  if (passengers >= 1 && passengers <= 4) {
    passengerresponse = "OK";
    cost += passengers / 10;
  }
  document.getElementById("passengers2").innerHTML = passengers;
  document.getElementById("totalcost").innerHTML = cost;
}
Journey in miles:
<input id="miles" type="number">
<p id="miles2"></p>

Number of passengers:
<input id="passengers" type="number">
<p id="passengers2"></p>

<button type="button" onclick="MyFunction()">Submit</button>

Total cost:
<p id="totalcost"></p>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
373 views
Welcome To Ask or Share your Answers For Others

1 Answer

passengers is a string, not a number. You're doing the same thing as saying cost = 'Santa' + 'Claus'; The fact that it's cost = '1' + '4'; doesn't change the '1' and '4' to a 1 and 4.

The solution is to use parseInt, Number, or one of the method from this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...