coder coder - 3 months ago 17
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 = event.target;
var maxlength = parseInt(obj.getAttribute('maxlength'), 10);
obj.value = obj.value.substring(0, maxlength);
obj.focus();
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

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 : https://jsfiddle.net/kyr6w2x3/55/

HTML:

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

JS:

   function AppViewModel(input) {
    this.zipCode = ko.observable(input).extend({ maxLength:5});
    this.phone = 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);
     if(newValue){
      target(newValue.substring(0, maxlength) ); 
     }

    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};

ko.applyBindings(new AppViewModel("12345678910"));
Comments