Im trying to create a custom binding to show hint texts in text inputs.
so far I have this but it doesnt work:
ko.bindingHandlers.hintText= {
init: function (element, valueAccessor) {
element.focus(function () {
if ($(this).val() === defaultText) {
$(this).attr("value", "");
}
});
element.blur(function () {
if ($(this).val() === '') {
$(this).val(valueAccessor());
}
});
}
}
the html:
<input id="profileID" type="text" data-bind="hintText:'Enter Profile ID'" />
The HTML5 placeholder
attribute should accomplish this for you.
If your browser requirements support the placeholder
attribute, you can call it directly using the KnockOutJS' attr
binding like this:
<input data-bind="attr:{placeholder: hintText}">
If you need support for older browser, there is a shim that should work for you: https://github.com/parndt/jquery-html5-placeholder-shim
In order to use this shim, you'd need to create custom binding so that you can manually call $.placeholder.shim();
as necessary when the placeholder changes.
Here's a "placeholder" binding that applies the shim (edited):
ko.bindingHandlers.placeholder = {
init: function (element, valueAccessor) {
var placeholderValue = valueAccessor();
ko.applyBindingsToNode(element, { attr: { placeholder: placeholderValue} } );
},
update: function(element, valueAccessor){
$.placeholder.shim();
}
};
Your html would then look like this:
<input data-bind="placeholder: hintText">