2016-07-23 85 views
-2

我對JavaScript很陌生,我想做一個輸入檢查。 這裏是我的腳本:這個數字腳本有什麼問題?

function checkInp() 
{ 
    var x=document.forms["myForm"]["num"].value; // Get the value 
    if (isNaN(x)) 
    { 
    alert("Not a number!"); // Check if the input is a number 
    return false; 
    } 
    var valuex=document.forms["myForm"]["num"].value; // Get the value, i don't know if i have to re-write this variable, if no, please comment. 
    Number(valuex); // Make the input a number 
    if (valuex.value > 480) { 
    alert("Too high!"); // See if the number is greater than 480. If yes, say that, if not, return normally. 
    return false; 
    } 
    else { 
    return; 
    } 
} 

我不知道發生了什麼,但自從我加入了第二部分的腳本不工作(檢查,如果數大於48​​0)。
請幫助我,如果可能,請用完整示例。

+0

你爲什麼要否決?有理由嗎? – MucaP

回答

0

的方式,我會做:

  • 文件selectorQuery是更容易理解
  • 不要多次獲得數值
  • 使用ParseInt轉換您的變數
  • 不要忘記返回真要是成功

代碼:

function checkInp() { 
    var x = document.querySelector('input[name="num"]').value; 
    if (isNaN(x)) { 
    alert("Must be a number"); 
    return false 
    } else if (x > 480) { 
    alert("Must be under 480"); 
    return false 
    } 
    return true 
} 
+0

謝謝。有效! – MucaP

+1

請注意,'parseInt()'用於**整數**,並且它允許尾隨非數字垃圾(所以「123hello world」被接受)。 – Pointy

+1

'!0'爲真,0肯定是一個數字。最好檢查'isNaN(x)'或'x!== x'。 'NaN'是JS中唯一不等於它自己的值 – Thomas

1

,如果我沒有錯,我thnk你只需要做的是這樣的:

If(valuex > 480)..