updating "placeholder" attribute using knockout

user1702964 picture user1702964 · Sep 28, 2012 · Viewed 22.7k times · Source

I have a form with some fields getting some data using knockout.js (ver. 2.1.0). For example, to update the "value" field of an input I put:

<input type="text"  name="contrasena" id="login-user" value="" placeholder="" data-bind="value: user">

I have a JSON to store the value a I want to use for "pass" keyword, and it works correctly.

I tried to set "placeholder" attribute using the same method, but it doesn't works:

<input type="text"  name="contrasena" id="login-user" placeholder="" data-bind="placeholder: user">

I tried to modify knockout.js file adding "ko.bindingHandlers['placeholder']" function based on "ko.bindingHandlers['value']" (modifying "placeholder" instead of "value" in "ko.jsonExpressionRewriting.writeValueToProperty" function), but it doesn't work correctly, it puts the information in "value" attribute instead of "placeholder".

Anyone knows the way to solve this?

Thank you very much!

Answer

gbs picture gbs · Sep 28, 2012

You should use the existing attr binding, like this:

<input data-bind="attr: {placeholder: ph}" />

var Model = function () {
    this.ph = ko.observable("Text..."); 
}
ko.applyBindings(new Model());