2015-10-18 62 views
1

我想在Javascript中執行一個錯誤檢查,如果表單文本元素爲空,它將彈出。檢查<form>文本元素是否爲空

var itemPrice = parseFloat(document.getElementById("tPrice").value); 

if(itemPrice < 0 || itemPrice == null) 
{ 
    alert("Please enter a valid price"); 
    return false; 
} 

我試過itemPrice == "null"itemPrice === "null"

任何有識之士都會很棒,謝謝!

+0

非常感謝您!我改變了我的if語句,並且它非常完美! if(itemPrice <0 || document.getElementById(「tPrice」)。value ==='') – Greg

+0

如果您喜歡其中一個答案,請接受它。 – Eric

回答

0

要檢查是否爲空值,只寫getElementById("tPrice").value===''沒有parseFloat。

var itemPrice = parseFloat(document.getElementById("tPrice").value); 

if(getElementById("tPrice").value==='' || itemPrice < 0) 
{ 
    alert("Please enter a valid price"); 
    return false; 
} 
0

這會給你的結果,你正在尋找

if (typeof itemPrice == "undefined" || itemPrice <= 0) { ... } 
0

可以使用isNaN函數來告訴我們函數是不是一個數字,它不僅適用於空/空值,也可爲任何隨機文本。

在下面的示例中,stackoverflow不允許alert語句運行,所以我將其更改爲內聯顯示結果。

function validateField() { 
 
    var itemPrice = parseFloat(document.getElementById("tPrice").value), 
 
     result = document.getElementById("result"); 
 
    
 
    if(isNaN(itemPrice) || itemPrice < 0) { 
 
     result.innerHTML = '<span style="background:red;color:#fff">Please enter a valid price</span>'; 
 
     return false; 
 
    } 
 
    result.innerHTML = '<span style="background:green;color:#fff">Price is valid</span>'; 
 
    return true; 
 
} 
 

 
<input type="text" id="tPrice" /> 
 
<button onclick="validateField();">Validate Field</button> 
 
Result:<span id="result"></span>

0

如果ITEMPRICE必須是一個數> 0試試這個:

var itemPrice = document.getElementById("tPrice").value; 

if(!(itemPrice > 0)) { 
    alert("Please enter a valid price"); 
    return false; 
}