Javascript code to set Rails date_select to today.

Posted by Bhushan Ahire | Posted in Rails | Posted on 03-09-2007

0

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.jsfunction 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>

How To pass Ruby Object to JavaScript function

Posted by Bhushan Ahire | Posted in Rails | Posted on 01-08-2007

0

If you want to pass ruby object to javascript function then do the followin steps…

In Ruby Controller Action…
def sample
ruby_variable = “Something”
ruby_variable.to_json
end

In Ruby RJS File

page.call ‘java_script_function_name’, ruby_variable

In JavaScript
function java_script_function_name(java_script_variable){
alert(java_script_variable);
}

java_script_variable comes in the form of array of javascript.
Add comments if anyone wants