Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

html - Javascript variables not adding two variables correctly, only concatenating

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...