6

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">
Kousha
  • 32,871
  • 51
  • 172
  • 296
Sudarshan Tanwar
  • 3,537
  • 3
  • 24
  • 39

2 Answers2

10

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

super cool
  • 6,003
  • 2
  • 30
  • 63
2

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>
    
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @mattytommo: Well, *someone* is missing the point. Again, `value` is a two-way binding. So a question [**stating** that binding](http://stackoverflow.com/revisions/30888954/1) is about two-way handling. No assumptions, no inferring. Also no flaming, I was just asking the OP to be clear about what they wanted. Which they've now done. – T.J. Crowder Jun 17 '15 at 10:51