Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails text_field default value disappear on click (and dimmed)

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!

like image 330
Brian Armstrong Avatar asked Sep 26 '09 16:09

Brian Armstrong


3 Answers

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

like image 87
llazzaro Avatar answered Oct 18 '22 18:10

llazzaro


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');
})
like image 23
Anatoliy Avatar answered Oct 18 '22 19:10

Anatoliy


Also check out HintValue, a JavaScript library that does this: http://projects.functino.com/hintvalue/

like image 21
Tom Söderlund Avatar answered Oct 18 '22 19:10

Tom Söderlund