Click here to Skip to main content
15,890,579 members
Articles / Web Development / HTML
Tip/Trick

Trimmed Value Binding in knockout.js

Rate me:
Please Sign up or sign in to vote.
4.86/5 (4 votes)
12 Jun 2014CPOL 23K   39   3   2
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)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionIt's not trim when you press "space" key ! Pin
Member 1111914929-Sep-14 16:49
Member 1111914929-Sep-14 16:49 
AnswerRe: It's not trim when you press "space" key ! Pin
DiponRoy29-Sep-14 19:50
DiponRoy29-Sep-14 19:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.