views:

38

answers:

4

I don't know if this is even possible, but in my rails app, I have this currently to put text in a text_field to be a description instead of having an external label:

      <% inside = "Search for Customers" %>
      <%= text_field_tag :search, params[:search],
                         :style => "color:#aaa;",
                         :value => inside, #defined above
                         :onfocus => "if(this.getValue()=='#{inside}'){this.clear();this.style.color = '#000';}",
                         :onblur => "if(this.getValue()==''){this.setValue('#{inside}');this.style.color = '#aaa';}" %>
        <%= submit_tag "Search", :name => nil %>

This works great, but if I don't enter anything in, it searches for "Search for Customers", which is not what I intended. Is there a way to fix this?

Thanks

Edit:

I've added a :onSubmit => "if(this.getValue()=='#{inside}'){this.clear();}" to the text_field_tag, but it's still not doing anything. I've also tried :onbeforesubmit and even a simple alert('test') but it's not working for some reason.

A: 

Fill inside by params[:search] if define

<% inside = params[:search] || "Search for Customers" %>
shingara
A: 

Not sure if rails makes it different, but you can usually use:

<form onbeforesubmit="someFunction()">

And then in somefunction() clear the textfield.

Litso
onbeforesubmit isn't working, at least in chrome it's not.
Reti
+1  A: 

There is a new placeholder attribute for inputs in HTML5, it does exactly what your asking for, but wont work for everyone yet.

http://diveintohtml5.org/detect.html#input-placeholder

You could use it and fallback to populating and clearing the field with the onsubmit event for people that have older browsers.

Jedidiah
There is some info about onsubmit here http://www.quirksmode.org/js/forms.html
Jedidiah
I'd rather not use HTML5 as I'm pretty sure 95% of my users won't be using modern browsers (unfortunately). Also, I tried the onSubmit thing, but it's not working :\ (see my edit in the OP)
Reti
Did you put the onsubmit on the form or the input?
Jedidiah
I put it on the text field
Reti
I think I need to put it on the button, but I'm not sure how to clear something in the text field from the button before it's submitted.
Reti
Ok, I think it would probably have to be on the form.
Jedidiah
Hmm, then it's not working how it should...
Reti
A: 

You may also simply ignore the request at the controller level if the search field is blank or if the search parameter corresponds to your inside string, something like:

def search
  if params[:search].blank? || params[:search] == "Search for Customers"
    return
  else
    do_whetever_you_want
  end
end
Yannis