Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert value into lower case before knockout binding

Demo Here

I bound a label with knockoutjs. The value bound always should be in lower case. While it will remain in uppercase in js model. How to do this ?

Javascript

var model = { 
    name:ko.observable("Test") 
}

ko.applyBindings(model);

HTML

<label data-bind="text:name">
like image 668
Sudarshan Avatar asked Jun 17 '15 10:06

Sudarshan


People also ask

What do you call to a function that converts a string into lower case?

lower() method returns the lowercase string from the given string. It converts all uppercase characters to lowercase. If no uppercase characters exist, it returns the original string.

What is binding in knockout?

Essentially a binding or a data binding is a way to link your ViewModels to your Views(templates) and vice versa. KnockoutJS uses two-way data binding, which means changes to your ViewModel influence the View and changes to your View can influence the ViewModel.

What is text binding?

Text binding causes the associated DOM element to display the text value of the parameter. This is used in text-level DOM elements such as <span> or <em>. The text binding accepts any data type and parses it into String before rendering it.


2 Answers

you just need to use toLowerCase in the view

view :

<div class='liveExample'>   
     <p> name: <label data-bind='text: name().toLowerCase()'></label></p> 
</div>

<b>Original Value:
<pre data-bind="text:ko.toJSON($data,null,2)"></pre>

sample working fiddle here

like image 106
super cool Avatar answered Oct 30 '22 14:10

super cool


It's unclear what you want to do, in particular when the value is coming from the textarea, but you can probably do whatever it is using a writable computed:

model.lowerName = ko.computed({
    read: function() {
        return model.name().toLowerCase();
    },
    write: function(newValue) {
        // ...save this however it is you want to save it...
    }
});

HTML:

<input data-bind="value:lowerName">

Re your updated question: Your update completely changes the question. If you don't need updates from the element and are only showing what's in name, you have two options:

  1. A read-only computed:

    model.lowerName = ko.pureComputed(function() { return model.name().toLowerCase(); });
    

    HTML:

    <label data-bind="text:lowerName"></label>
    
  2. Just do it in the binding:

    <label data-bind="text:name().toLowerCase()"></label>
    
like image 30
T.J. Crowder Avatar answered Oct 30 '22 14:10

T.J. Crowder