On 7/20/05, Chad Lung <chad.lung-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:> I''ve looked around the Rails documentation as well as the PDF
version
> of the Agile Rails book looking for a way to set a default text_field
> control and cannot seem to find anything. Is this something that is
> not currently baked into the Rails API? I can do this in JavaScript
> of course, but was thinking Rails probably already did this for me in
> some nifty fashion.
On preview, I realized you *may* have meant "default" as in,
"default
value". However, read on for a lengthy diatribe on setting the focus,
and some more on default values below that :)
----
Nope! However, this probably would be a good patch to make.
The easiest way to do it, would be just to embed a script tag
<script>$(''your_element'').focus();</script>
directly *after* the element. But don''t tell the standards weenies!
And, you''ll need a DOM id for the input tag.
Alternatively, you''ll be able to call this with some kind of dynamic
window onload function [1], but remember this won''t fire until the
whole page is loaded (there can be some delay). Also, you''re going to
need to modify the page''s content_for_head, and, make sure people are
including <%= @content_for_head %> in the appropriate part of the
page.
Or, finally, you could set a class, then, in your window onload,
select all input elements and textarea elements, check if their class
matches /\bfocus\b/, and focus the first one. Actually I think there''s
some functions in prototype like getElementsByClassName.
While the final method is probably the most fashionable (behavior,
anyone), the first one will be the easiest to apply with to the
framework, as, AFAIK, there is no existing way that the framework can
insert script into the window onload event.
---------
What you probably wanted was default value, which is removed when you
enter the field. This also not implemented, and would also be a good
patch :)
<input type=''text'' value=''monkey''
onfocus=''if (this.value =this.defaultValue) this.value = "";
this.removeClassName("default");''
onblur=''if (this.value == "") this.value = this.defaultValue;
this.addClassName("default");'' />
..and set your styles to make "default" grayed out or something.
courtenay
habtm.com
-----
[1] can''t recall who I sto^H^H^H borrowed this from, but it''s
a nifty one..
function _add_onload(func) {
var old = window.onload;
if (typeof window.onload != ''function'')
window.onload = func;
else window.onload = function() {
old();func(); };
}
Call it with
_add_onload(function() { ... your code ..} );