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