Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Trimmed Value Binding in knockout.js

4.86/5 (4 votes)
12 Jun 2014CPOL 23.4K   39  
Trimmed value binding in knockout.js

Introduction

In web applications, when we are working with form inputs; sometimes we have to trim the user input values to avoid unnecessary white spaces. So every input value needs to be trimmed and use of so many $.trim() comes ahead.

Background

As the number of input grows, so does the use of $.trim(). And try to imagine doing the same thing in every form. To avoid such massive use of $.trim(), we can use custom knockout value binding handler which will ensure that if the user inputs/server send the value with unnecessary white spaces, it would be trimmed and will be reassigned to the input field.

Custom Binding Handler

Here is the custom binding handler which will help use in trimmed value binding:

JavaScript
/*trimmed value binder for knockout*/
ko.bindingHandlers.trimedValue = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        $(element).on("change", function () {
            var observable = valueAccessor();
            var trimedValue = $.trim($(this).val());
            observable($(this).val());
            observable(trimedValue);
        });
    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var trimedValue = $.trim(value);
        $(element).val(trimedValue);
    }
};

Using The Handler In HTML

We are going to use the handler like this. It's really important to remember to use data-bind="trimedValue: " rather than data-bind="value: "

HTML
<h2>Trimed value building</h2>
<div>
    <span>change the values to see if triming is taking place or not</span>
    <!--First Name-->       
    <div>
        <label>First Name</label>
        <input type="text" data-bind="trimedValue: firstName" />
    </div>
    <!--Last Name-->       
    <div>
        <label>Last Name</label>
        <input type="text" data-bind="trimedValue: lastName" />
    </div>
    <!--Age-->       
    <div>
        <label>Age</label>
        <input type="text" data-bind="trimedValue: age" />
    </div>            
</div>

View Model

Now let's see the view model:

JavaScript
/*View model*/
function ViewModel() {
    var self = this;
    self.firstName = ko.observable('');
    self.lastName = ko.observable('');
    self.age = ko.observable(0);
    
    /*initialize vm*/
    self.init = function () {
        self.firstName('   Dipon   ');      // only 'Dipon' would be bind to model
        self.lastName('   Roy    ');        // only 'Roy' would be bind to model
        self.age('  24 ');                  // only '24' would be bind to model
    };
}

Finally, apply view model binding:

JavaScript
$(document).ready(function () {   
    //model binding with validation
    var vm = new ViewModel();
    vm.init();
    ko.applyBindings(vm);
});

Find the JsFiddel example at http://jsfiddle.net/DiponRoy/Ygey4/2/.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)