3

I have an input field and i want to restrict it only for numeric values. How can i do it in knockout js

here is my field

 <input data-bind="value: nsc" />
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user2142786
  • 1,484
  • 9
  • 41
  • 74

2 Answers2

4

You can write a function in your view model.

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;

};

Check this link how to use : Sample code

Seminda
  • 1,745
  • 12
  • 15
  • 1
    This is by far the best way to do it. (Also better than the accepted answer in the link @Raghavendra-N posted). This is mainly because of two reasons: an extender is much more flexible than a custom binding, and it promotes better code separation. By that I mean that it makes more sense to put the restriction of numeric-only in your JavaScript, since it represents domain logic, than in your HTML which is concerned with presentation. – Hans Roerdinkholder Aug 28 '14 at 08:49
  • Hi Hans, Can you answer this question http://stackoverflow.com/questions/25637663/converting-circular-structure-to-json-in-knockout-js – user2142786 Sep 03 '14 at 07:06
0

Guess this question is already answered. You may need to create custom binding which accepts only allowed characters.

The answer to the post in this link will help you: make an input only-numeric type on knockout

Community
  • 1
  • 1
Raghavendra N
  • 1,359
  • 1
  • 18
  • 36
  • The answer given here by @Seminda is much better than the answer in the question you linked. A custom binding is not the ideal solution for this, an extender is far more flexible and also provides better code separation (your HTML should not dictate your domain logic, your JavaScript should). – Hans Roerdinkholder Aug 28 '14 at 08:51