2017-07-06 71 views
-3

由於某種原因,當我輸入值時,所有的輸出是 undefined,NaN和我不知道爲什麼。我認爲 錯誤真的很簡單..所以我簡單的facepalm。對於我的代碼,對不起 ,我還是新來的JavaScript。另外,不要介意信用卡。爲什麼我的輸出Undefined或NaN?

function processAmount(){ 
    var numOfLiters= parseInt(document.estore.noOfLiters.value); 
    var result; 
    var perLiterAmount; 
    var gasType; 

    switch(gasType){ 
    case "Premium": 

      perLiterAmount= 50; 
      result= 50*numOfLiters; 
      break; 
    case "Diesel": 
      perLiterAmount= 38; 
      result= 38*numOfLiters; 
      break; 

    case "Unleaded": 
      perLiterAmount= 44; 
      result= 44*numOfLiters; 
      break; 
    } 



    var vat= result*0.12; 

    document.write("<p>Fuel Type: " + gasType + "</p>"); 
    document.write("<p>Price per Liter amount: " + perLiterAmount + "</p>"); 
    document.write("<p>Purchase Amount: " + result + "</p>"); 
    document.write("<p>VAT: " + vat + "</p>"); 
    document.write("<p>TOTAL AMOUNT: " + (result+vat) + "</p>"); 
    document.write("<p>Credit Card : " + creditCard + "</p>");` 

,這裏是形式:

<form name='estore' id='estore'> 
    <fieldset> 
      <legend>Gasoline eStore</legend> 
       <p>Enter gasoline type: 
        <select name='gastype' id='gastype'> 
         <option value="Premium"> Premium</option> 
         <option value="Unleaded"> Unleaded</option> 
         <option value="Diesel"> Diesel</option> 
         </select></p> 

       <p> Enter number of Liters: 
        <input type='number' name='noOfLiters' id='noOfLiters'/> 
       </p> 

       <p> Enter Credit Card Number: 
        <input type="number" name='creditCardNumber' id='creditCardNumber'/> 
       </p> 

       <p> 
        <input type='button' value='Submit' 
         onclick="processAmount()"/>&nbsp;&nbsp;&nbsp; 
        <input type='reset'/> 
       </p>  
+1

什麼是gasType? –

+1

因爲'gasType'沒有被初始化。 –

回答

0

您可以用

var gasType = document.getElementById('gastype').value; 

這樣,你的方法processAmount()應該像預期的那樣取代

var gasType; 

。 由於這裏已經提出了一些其他的回覆,你沒有初始化變量gasType,所以它是undefined

使用上面的命令行,使用select字段中的值初始化它。

2

首先值分配給gasType,然後把它放在switch情況。

+0

* facepalm *非常感謝! – AGirlisnoone

0

在你的函數分配值gastype

var gastype = $('#gastype :selected').val(); 
+1

這需要作者使用jQuery,但它看起來不像他們的代碼。所以,作者,如果你想使用這段代碼,確保你的項目包含jQuery作爲依賴。 –

相關問題