2016-04-06 18 views
1

okey所以我得到了這個,有點看看它像你有一個網站是你可以兌換點,現在當我點擊贖回我不希望給出的數字小於4分和給出的數字大於你的平衡點數。Javascript如果功能不正常與getElemenById

現在,當我點擊按鈕,當輸入爲2,我將獲得2個警報(警報是用於測試)

但是,只要我按一下按鈕,當我把比我的資產負債較少的數量,我也會得到2個警報,說數字=(例如)7和平衡隱藏= 100.所以我不明白爲什麼我會得到這些警報。因爲它比平衡和大於4

也是這個領域的平衡得到存儲時refreshBalance()被調用較小:

<input type=hidden id="balancehidden" name="balancehide" 
         value=""/> 

的Javascript:

<input type="text" id="number"><br> 
     <button type="button" class="btn btn-success" id="redeem">Redeem</button> 

    <body onload="refreshBalance()"> 

      <script type="text/javascript"> 

      document.getElementById('redeem').onclick = function() { 

      if(document.getElementById('number').value < 4 || document.getElementById('number').value > document.getElementById("balancehidden").value) 
      { 


      alert(document.getElementById("number").value); 
      alert(document.getElementById("balancehidden").value); 
      } 
      } 
      </script> 
+0

PLZ解釋爲什麼downvote? im new sry – Nick

+0

爲什麼你的'input'和'button'標籤在體外?那些應該在你的身體內。 – litel

+0

對不起忘了提及這是我的php文件snipet – Nick

回答

3

你試圖查看一個字符串是否大於另一個字符串,但你真正想要做的是比較數字。 直覺上,"4" > "100" === true4 > 100 === false。 轉換你的價值觀爲數字:

if(parseInt(document.getElementById('number').value) < 4 || parseInt(document.getElementById('number').value) > parseInt(document.getElementById("balancehidden").value)) 

使用parseFloat而不是parseInt,如果你希望小數,並意識到了radix parameter的。

+0

感謝您的解決方案! – Nick

2

問題是您正在嘗試比較字符串值而不是整數。 請工作代碼檢查此的jsfiddle:​​

document.getElementById('redeem').onclick = function() { 
    var number = parseInt(document.getElementById('number').value); 
    var balance = parseInt(document.getElementById('balancehidden').value); 
    if(number < 4 || number > balance) { 
    alert(document.getElementById("number").value); 
    alert(document.getElementById("balancehidden").value); 
    } 
} 
+0

感謝您的解決方案! – Nick