coder coder - 1 year ago 92
Javascript Question

JavaScript event, not updating knockout observable/model value

I have text field which is wired up with Keyup & change event, to trim the field length.

@Html.TextBoxFor(m => m.zipCode, new {data_bind = "textInput: zipcode, event: { keyup: trimField, change: trimField }", maxlength = "5"})

Trim function,

function trimField(data, event) {
var obj =;
var maxlength = parseInt(obj.getAttribute('maxlength'), 10);
obj.value = obj.value.substring(0, maxlength);
return true;

If I type "123456", on the UI it shows "12345", but the model has "123456".

How to get model updated after the keyup event?

Answer Source

You are not updating the observable variable which is bound to your element. It is better to make it generic as an observable extend so it can be used everywhere based on your max-length and to make sure it follows your rule for an initial value.

Example :


 <input data-bind='textInput: zipCode' />
   zip code in Model:<span data-bind="text:zipCode"></span>


   function AppViewModel(input) {
    this.zipCode = ko.observable(input).extend({ maxLength:5}); = ko.observable(input).extend({ maxLength:11});

 ko.extenders.maxLenght = function(target, characters) {
    target.validationMessage = ko.observable();

    //define a function to do validation for maxLength
    function validate(newValue) {

    var maxlength = parseInt(characters, 10);
      target(newValue.substring(0, maxlength) ); 


    //initial validation

    //validate whenever the value changes

    //return the original observable
    return target;

ko.applyBindings(new AppViewModel("12345678910"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download