JSF: Prefilled values with input text field?
I tried searching, but haven't found the answer. I see when you ask a question on stackoverflow, the input field for "tags" show the gray text "at least one tag such as...etc". Upon click, the gray text disappears and you can start typing your values. If I click off that, the instructions reappear. How do I do that? Are there out of box implementation开发者_如何学Pythons of this functionality or does this require custom implementation?
Thanks!
Two JSF component libraries offering this functionality comes to mind:
- OpenFaces input text with Prompt text
- PrimeFaces Watermark
It's a blur/focus javascript event handler on the input field. In jQuery it would be something like the following:
HTML
<input type="text" name="your-input" id="your-input" title="Enter a value"/>
jQuery
$('#your-input').focus(function(){
var defaultVal = $(this).attr('title');
if($(this).val() == defaultVal)
$(this).val('');
});
$('#your-input').blur(function(){
var defaultVal = $(this).attr('title');
if($(this).val() == '')
$(this).val(defaultVal);
});
$('#your-input').trigger('blur');
It takes the default value from the input's title
attribute and sets its value on focus and blur events depending on the current value of the input. The last trigger()
call is so the input's value is correctly set when the page loads.
You can see it in action here.
The simplest example would be
window.onload = function() {
var txtField = document.getElementById('textField');
if(!txtField.value) {
txtField.value = 'Default Text';
}
}
<h:inputText id="txtField" value="#{bean.txtField}"
onfocus="window.default=this.value; this.value='';"
onblur="if(!this.value) { this.value = window.default; }"/>
In any case I would suggest to switch the window.onload to any dom ready function such as
document.observe('dom:loaded', function(){}); // Prototype
$(document).ready(function(){}); // jQuery
精彩评论