javascript 如何检查文本框是否为非空且其值是否大于 0 而不是文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4851887/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if textbox is non-empty and that its value is greater than 0 and not text?
提问by TheBlackBenzKid
I want to check if a textbox value is empty and also if the textbox is greater than 0 with IF OR function via Javascript.
我想检查文本框值是否为空,以及文本框是否大于 0 使用 IF OR 函数通过 Javascript。
My code is below:
我的代码如下:
if(qty != "" && qty <> "0"){
//
}
Where qty is the name and id of the HTML input field
其中 qty 是 HTML 输入字段的名称和 ID
THIS IS THE SOME PORTION FROM THE FULL UPDATED CODE.
这是完整更新代码的一部分。
    if(qty != "")
    {
if(/^\d+$/.test(qty.value)){
var value = parseint(qty.value, 10);
sizeID = document.getElementById("size" + colID + prodID).value;window.location = "/_nCartAddToBasket.asp?ProductID=" + prodID + "&ProductColourID=" + colID + "&ProductSizeID=" + sizeID + "&Qty=" + qty + "&fgID=" + fgID;
}else{
alert("You must enter a numeric value in the quantity field.");}
}else{
alert("You must enter a quantity before adding to your basket.");}
}
回答by Pointy
I edited your question a little in order to have it make some sense. Your text element cannot be both empty and greater than zero at the same time.
我对您的问题进行了一些编辑以使其有意义。您的文本元素不能同时为空和大于零。
var qty = document.getElementById('qty');
if (/^\d+$/.test(qty.value)) {
  var value = parseint(qty.value, 10);
  // whatever ...
}
That makes sure that the value of the text element is a string of one or more digits.
这确保文本元素的值是一个或多个数字的字符串。
回答by Brad Christie
var tbVal = parseInt(document.textbox.value,10) // or jQuery: parseInt($('#textbox').val(),10);
if (!isNaN(tbVal) && tbVal > 0){
  document.textarea.value = tbVal // $('#textarea').val(tbVal);
  // code here
}
回答by Danilo
according to what you wrote, you may like a check like this one
根据你写的,你可能喜欢这样的支票
<script>
function check(value){
if(value=="" || (typeof(value==='number') && value > 0))
alert("The textfield is empty OR its content (value) is a number greater than 0 (> 0)");
}
</script>
<input type="text" onBlur="check(this.value)"/>
回答by szeliga
var textbox = $get(id);
if(textbox && typeof(textbox.value) == 'number' && textbox.value > 0)
{
//do something here
}

