2014-08-28 46 views
1

我有一個輸入字段,我想限制它只用於數值。我怎樣才能做到這一點在這裏淘汰賽JS如何限制輸入字段數字在淘汰賽js

是我的領域

<input data-bind="value: nsc" /> 
+0

利用基因敲除驗證 – 2014-08-28 07:01:45

+0

通過@Seminda這裏給出的答案比你鏈接的問題的答案要好得多。 – 2014-08-28 08:50:56

回答

0

想這問題是已經回答了。 您可能需要創建只接受允許的字符的自定義綁定。

這個問題的答案在此鏈接後會幫助你:make an input only-numeric type on knockout

+0

@Seminda給出的答案比你鏈接的問題的答案要好得多。自定義綁定不是理想的解決方案,擴展器更加靈活,並且提供更好的代碼分離(您的HTML不應該規定您的領域邏輯,JavaScript應該)。 – 2014-08-28 08:51:55

4

你可以寫在你的視圖模型的功能。

ko.extenders.numeric = function(target, precision) { 
//create a writable computed observable to intercept writes to our observable 
var result = ko.pureComputed({ 
    read: target, //always return the original observables value 
    write: function(newValue) { 
     var current = target(), 
      roundingMultiplier = Math.pow(10, precision), 
      newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue), 
      valueToWrite = Math.round(newValueAsNum * roundingMultiplier)/roundingMultiplier; 

     //only write if it changed 
     if (valueToWrite !== current) { 
      target(valueToWrite); 
     } else { 
      //if the rounded value is the same, but a different value was written, force a notification for the current field 
      if (newValue !== current) { 
       target.notifySubscribers(valueToWrite); 
      } 
     } 
    } 
}).extend({ notify: 'always' }); 

//initialize with current value to make sure it is rounded appropriately 
result(target()); 

//return the new computed observable 
return result; 

};

檢查此鏈接如何使用:Sample code

+1

這是迄今爲止最好的方法。 (也比鏈接@ Raghavendra-N發佈的接受的答案更好)。這主要是因爲兩個原因:擴展器比自定義綁定更靈活,並且它促進了更好的代碼分離。因此,我的意思是將數字限制在JavaScript中是比較合理的,因爲它代表域邏輯,而不是在與呈現相關的HTML中。 – 2014-08-28 08:49:58

+0

嗨漢斯,你能回答這個問題嗎?http://stackoverflow.com/questions/25637663/converting-circular-structure-to-json-in-knockout-js – user2142786 2014-09-03 07:06:21