Topic: Handy RJS Tips
Here's a few RJS tips that don't seem to be documented very well. If you have a tip to share, please add it to this thread.
Outputting Javascript Directly
RJS is very convenient, but sometimes you want to do something which is not directly supported through RJS. You can output any kind of JavaScript you want like this:
page << "document.forms[0].reset();"
This will call reset on the first form in the document, just as if you typed the javascript directly inline!
Selecting Multiple Tags
Prototype offers the ability to select HTML elements through a powerful CSS like syntax. Ruby makes this even more powerful by allowing you to use Ruby blocks to iterate through the selected HTML elements. For example.
page.select('form').each { |f| f.reset }This will reset all of the forms on the page. As mentioned the selectors are similar to CSS, so you can do this:
page.select('.book').each { |b| b.hide }This will hide all of the elements with the class 'book'. Very handy!
Specifying Element
Most RJS helper methods take the name of the element as the first parameter. For example:
page.replace_html :greeting, 'Hello World!'
This will find an HTML element with the id 'greeting' and replace its content with "Hello World!". Instead of specifying the DOM id as the first element, you can place it in square brackets like this:
page[:greeting].replace_html 'Hello World!'
This feels better to me.
Setting Element Attributes
Let's say you have a text field:
<%= text_field_tag :search %>
And you want to set the value of this text field through RJS dynamically. No problem, just grab the element as shown previously, then set the 'value' attribute just like you would a normal Ruby object.
page[:foo].value = 'Search Here!'
That is so cool!
Last edited by ryanb (2006-10-31 14:06:42)