These text fields look great and are common on web 2.0 sites like Facebook.
Basically instead of labeling the text field, you can save space by putting the label inside the text field. Typically the text is dimmed in color a bit, and when the user clicks in the text field the default value disappears, and the color switches to black or the regular color so the user can enter text.
So far this is how I've been creating them:
# DEFAULT_VALUE = "email address"
<%= f.text_field :email,
:style => "color:#aaa;",
:value => DEFAULT_VALUE,
:onfocus => "if(this.getValue()=='#{DEFAULT_VALUE}'){this.clear();this.style.color = '#000';}",
:onblur => "if(this.getValue()==''){this.setValue('#{DEFAULT_VALUE}');this.style.color = '#aaa';}" %>
This basically works. But one problem I've noticed is that if you type something in the field and submit a form that fails, the form will reload with what you typed in the field (as it should) but the text is incorrectly dimmed. This also happens if you click back on your browser..it will display the text you entered (not the default value) but the text color is dimmed.
Is there an easier way to do this or way to solve the above problem? Thanks!
For newer version of rails you should use
text_field_tag 'search', nil, :placeholder => 'Enter search term...'
check here for the text_field_tag documentation
This is because
:style => "color:#aaa;",
You should add condition, that checks entered value and default value.
upd: sample of client side ckeck jquery:
$(document).ready(function () {
$input = $('input#id');
$input.css('color', $input.val() === DEFAULT_VALUE ? '#aaa' : '#000');
})
Also check out HintValue, a JavaScript library that does this: http://projects.functino.com/hintvalue/
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