2014-04-06 16 views
0

我有一个在猫鼬模式的JavaScript来自动增加一个值,如果没有在表单字段中手动输入数字。Javascript'如果'查看表单域是否有数字?

// before validation starts, the number of Items is counted..afterwards, the position is set 

    ItemSchema.pre("validate", function(next) { 

     var doc = this; 

     // if 'position' is not filled in, fill it in..not using !position because 0 might be a valid value 
     if(typeof position !== "number") { 
      // count the number of Items * 
      // use mongoose.model to fetch the model because the model is not compiled yet 
      mongoose.model("Item").count(function(err, num) { 
       // if there was an error, pass it to next() 
       if(err) 
        return next(err); 

       // set the position, then call next(); 
       doc.position = num; 
       return next(); 
      }); 
     } else if(this.isModified("position") || this.isNew()) { 
      // code to check if there is an existing document with the same position 
      // code to check move down other document positions, if existing 

自动递增工作正常,但它是这样做的,无论该字段中是否有数字。什么是更好的“如果陈述”通过?

我有这个表单域的前端:

<input type="number" class="form-control input-lg text-center" placeholder="Position" ng-model="formData.position"> 

而且我知道数据是通过

position : req.body.position, 

因为console.log(req.body.position);不登录数量

+0

目前还不清楚你的代码是如何/何时执行的,以及每个事物如何相互关联。如果不清楚您的代码的作用,很难提供帮助。 –

+0

如果'position'从HTML元素中填充,它将是一个*字符串值*。在Stack Overflow上有很多关于检查值是否是数字的帖子。 –

+0

我猜'position'是值,并且总是一个字符串,因此检查typeof失败。你想'isNaN' – adeneo

回答

0

经过试试这个:

parseFloat()将返回一个空 NaN的根据您的浏览器的时代。如果传递错误值(NaN,undefined)或null,则'或'函数将返回辅助(在本例中为-1)。您可以更改以将-1值更改为任何您想要的值。我只是喜欢数字,因为他们占用了几个字节的内存然后是字符串,并且处理速度更快。

+0

这将返回一个ReferenceError:位置未在控制台中定义,并在浏览器网络上500内部服务器错误..谢谢虽然 – StackThis

相关问题