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!
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());
If you want to use data-bind="placeholder: user"
, you can create a custom-binding in your js code.
You were on the right path using ko.bindingHandlers['placeholder']
but you don't need to edit the knockout.js file -- in fact, that is bad practice.
This would require a very basic custom-binding:
ko.bindingHandlers.placeholder = {
init: function (element, valueAccessor, allBindingsAccessor) {
var underlyingObservable = valueAccessor();
ko.applyBindingsToNode(element, { attr: { placeholder: underlyingObservable } } );
}
};
For a guide on custom-bindings, see here
Although Knockout is itself inherently obtrusive, this is slightly less. It removes the knowledge of how the placeholder is applied to the element from the view.
In fact, if in the future you wanted to apply some sort of jQuery plugin to show placeholders in browsers which don't support the placeholder
attribute, this would be the place (init:
) to initialise the plugin -- you would also need an update:
function in that case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With