私は、ユーザーが書き込むテキストボックスの値と以前に使用された計算値から数値を取って計算する関数を使用していますページのテキストボックスの値が正の数でない場合は、値が正の数でなければならないことを示すアラートが表示されます。正の数であれば、数学の結果を示す警告が表示されます。唯一の問題は、これが起きたときに表示されるのは、数字がどこにあるべきかということです。代わりに「NaN」です。これは、私が使用している値が実際に数値ではないので、これを解決する方法がわからないからです。テキストボックス値と計算値で計算するのに問題があります
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = (total/1000) * 0.621371;
document.getElementById('total').innerHTML = total;
}
function calc_gallons() {
var total = parseInt(document.getElementById("total").value)
\t \t var averagempg = parseInt(document.getElementById("averagempg").value);
\t \t var gallons = 0;
\t \t if (averagempg > 0) {
\t \t \t gallons = total/averagempg
\t \t \t window.alert("This trip requires " + gallons + " gallon(s). Have safe travels!");
\t \t }else {
\t \t \t window.alert("Your average MPG must be a positive number in order to calculate the gallons required for this trip.");
\t \t }
}
#this is the text box and the button that does the function
<p>Your Average MPG:<input type="text" id="averagempg" name="MPG"></p>
<button type="button" name="Calculate" onclick="calc_gallons()">Calculate!
私はID 'averagempg'で任意の要素を見ていませんよ。あなたのコンソールにエラーがありますか? – yezzz
不思議ではありません。そのスニペットを含めるのを忘れてしまったので、平均化されていません。 –