【问题标题】:How to check if textbox is non-empty and that its value is greater than 0 and not text?如何检查文本框是否为非空且其值是否大于 0 而不是文本?
【发布时间】:2011-01-31 14:16:30
【问题描述】:

我想通过 Javascript 使用 IF OR 函数检查文本框的值是否为空,以及文本框是否大于 0。

我的代码如下:

if(qty != "" && qty <> "0"){

//

}

其中 qty 是 HTML 输入字段的名称和 ID

这是完整更新代码的一部分。

    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.");}
}

【问题讨论】:

  • 你是指文本字段还是文本区域?
  • Textfield code 输入数量:

标签: javascript ajax xhtml input


【解决方案1】:

我稍微编辑了你的问题,以便让它有意义。您的文本元素不能同时为空和大于零。

var qty = document.getElementById('qty');

if (/^\d+$/.test(qty.value)) {
  var value = parseint(qty.value, 10);
  // whatever ...
}

确保文本元素的值是一个或多个数字的字符串。

【讨论】:

    【解决方案2】:
    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
    }
    

    【讨论】:

    • 这是正确的 除了 parseInt() 不关心某些数字后是否有垃圾 - 换句话说,parseInt("12hello") 返回数值 12 并且不抱怨关于“你好”。
    • @Pointy:是的,我可能应该修改它以重新分配解析值。好电话。
    【解决方案3】:
    var textbox = $get(id);
    if(textbox && typeof(textbox.value) == 'number' && textbox.value > 0)
    {
    //do something here
    }
    

    【讨论】:

    • $get() 是 document.getElementById() 的简写,但仔细想想,它可能只适用于 .NET 实例。抱歉应该提到,使用 .NET 太久了,它已成为第二天性。
    【解决方案4】:

    根据你写的,你可能会喜欢这样一张支票

    <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)"/>
    

    【讨论】:

    • 文本元素的 value 属性在用户交互后始终为字符串。
    猜你喜欢
    • 2012-04-26
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2010-12-06
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多