The default value for Rails text_field disappears when clicked (and dims)

These text boxes look great and are common on 2.0 websites such as Facebook.

Basically, instead of labeling a text field, you can save space by placing a label in the text field. Typically, the text is colored a little, and when the user clicks the text field, the default value disappears, and the color switches to black or normal color, so the user can enter text.

So far I have created 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';}" %> 

It basically works. But one of the problems that I noticed is that if you enter something in the field and submit the form that fails, the form will reload with what you typed in the field (as it should be), but the text is incorrect blurred. This also happens if you click on your browser ... it will display the entered text (and not the default value), but the color of the text will be darkened.

Is there an easier way to solve this problem or solve this problem? Thanks!

+6
javascript ruby-on-rails
source share
3 answers

It's because

 :style => "color:#aaa;", 

You must add a condition that validates the entered value and the default value.

upd: ckeck jQuery client side sample:

 $(document).ready(function () { $input = $('input#id'); $input.css('color', $input.val() === DEFAULT_VALUE ? '#aaa' : '#000'); }) 
+3
source share

For a newer version of rails you should use

text_field_tag ​​'search', nil ,: placeholder => 'Enter a search query ...'

here for text_field_tag ​​documentation

+5
source share

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

+1
source share

All Articles