Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  162] [ 2]  / answers: 1 / hits: 17400  / 12 Years ago, wed, november 28, 2012, 12:00:00

I've seen this post - it shows one possible solution. But I would like to have a more elegant way of doing masked input.



It should also play nicely with knockout validation plugin (or maybe extending it).



Anyone know how is there similar project out there?


More From » knockout.js

 Answers
0

If you wanted to use the excellent Masked Input Plugin in Knockout, it's pretty easy to write a basic custom binding rather than an extender.



ko.bindingHandlers.masked = {
init: function(element, valueAccessor, allBindingsAccessor) {
var mask = allBindingsAccessor().mask || {};
$(element).mask(mask);
ko.utils.registerEventHandler(element, 'focusout', function() {
var observable = valueAccessor();
observable($(element).val());
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).val(value);
}
};


And then in your HTML:



<input type=text data-bind=masked: dateValue, mask: '99/99/9999' />
<input type=text data-bind=masked: ssnValue, mask: '999-99-9999' />


And so on with various masks. This way, you can just put the mask right in your databinding, and it allows a ton of flexibility.


[#81754] Tuesday, November 27, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ignacio

Total Points: 467
Total Questions: 128
Total Answers: 79

Location: Luxembourg
Member since Tue, Mar 14, 2023
1 Year ago
ignacio questions
;