user2744722 user2744722 - 2 months ago 13
Javascript Question

applying jasny input mask on knockout load

I am attempting to apply the jasny bootstrap input mask to a text input that is databound using knockout. however the datamask does not show up until you click on the input box. I'm not sure why. I would like the input mask to show up right away. here is the fiddle. http://jsfiddle.net/LkqTU/31938/

here is the html

<div class="container">
<table class="table table-condensed table-hover">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody data-bind='foreach: employees'>
<tr>
<td data-bind='text: firstName'></td>
<td data-bind='text: lastName'></td>
<td>
<input type="text" class="form-control" data-bind="value: phone" data-mask="999-999-9999">
</td>
</tr>
</tbody>
</table>
</div>


and here is the javascript.

function employee(firstName, lastName, phone) {
this.firstName = ko.observable(firstName);
this.lastName = ko.observable(lastName);
this.phone = ko.observable(phone);

}

function model() {
var self = this;
this.employees = ko.observableArray("");
}

var mymodel = new model();

$(document).ready(function() {
loaddata();
ko.applyBindings(mymodel);
});

function loaddata() {
mymodel.employees.push(new employee("Bob", "Jones", "7174569876"));
mymodel.employees.push(new employee("Mary", "Smith", "3457892435"));
mymodel.employees.push(new employee("Greg", "Black", "3557689800"));
}

Answer

Try initializing the input mask on document load, after your Knockout bindings have been applied:

$(document).ready(function () {
    loaddata();
    ko.applyBindings(mymodel);
    $('.form-control').inputmask({
      mask: '999-999-9999'
    })
});

Be sure to remove your data-mask attribute as well.

JS Fiddle example

Comments