Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Javascript code to set Rails date_select to today. (See related posts)

If you are using date_select in rails here is a little bit of javascript so that at the side of the fields the user can click a link that will automatically set the fields to todays date.

Updated: Now works on rails 1.2, as date_select now finally has ids
# put is app_root/public/javascript/application.js

function set_today(model, atrib)
{
    t3 = document.getElementById(model + '_' + atrib + '_3i');
    var dt = new Date(); 
    t3.selectedIndex = dt.getDate();
	
    t2 = document.getElementById(model + '_' + atrib + '_2i')
    t2.selectedIndex = dt.getMonth() + 1;
    
    t1 = document.getElementById(model + '_' + atrib + '_1i')

    for (i = 0; i < t1.length; i++)
	       {
	           if (t1.options[i].text == dt.getFullYear())
	           {
	               t1.selectedIndex = i;
	          }
    } 
}





To call this method say in a link use this in your rhtml

<a href="javascript: set_today('model_name', 'column_name');">today?</a>

Comments on this post

thunder posts on Jan 18, 2007 at 22:36
This method works fine in IE, but does not work with Firefox. The debug console indicates that "t3 (or t2, t1) has no properties". Basically, document.getElementById(model + '[' + atrib + '(3i)]') returns NULL in Firefox. Are there any way I can work around this so that the code would be good for both IE and FF? I tried getElementsByName and getElementsByTagName, but IE has problem with them. I probably did something wrong. Any idea?
thunder posts on Jan 19, 2007 at 21:23
#I changed code as the following and it worked in both IE and Firefox.
#The added logic was used to handle blank (null) date, which is an option in my project.

function set_today(model, atrib)
{
var dt = new Date()

t3 = document.getElementsByName(model + '[' + atrib + '(3i)]')
if (t3[0].length == 31) {t3[0].selectedIndex = dt.getDate() - 1}
else {t3[0].selectedIndex = dt.getDate()}


t2 = document.getElementsByName(model + '[' + atrib + '(2i)]')
if (t2[0].length == 12) {t2[0].selectedIndex = dt.getMonth()}
else {t2[0].selectedIndex = dt.getMonth() + 1}

t1 = document.getElementsByName(model + '[' + atrib + '(1i)]')
for (i = 0; i < t1[0].length; i++)
{
if (t1[0].options[i].text == dt.getFullYear())
{
t1[0].selectedIndex = i;
}
}
}
jeffguroo posts on Jan 25, 2008 at 16:20
<%= select_date(Time.now, :order=>[:year,:month,:day], :prefix =>"date_name") %>

Does the same thing without the use of js.

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts