Javascript code blocks in RJS

Hi all:

I have a block of javascript that I want to use to clear out field
notices in multiple forms on my site.

The way I’m doing it now is to write directly to RJS like

render :update do |page|
page << JS_BLOCK

with the code block assigned as a string to a variable at the
ApplicationController level like

JS_BLOCK = “var notice_fields =
for(var i=0;i<notice_fields.length;i++) notice_fields[i].innerHTML= ‘’”

Is there a better way of handling reused js code within RJS?


You could store the commands in an rjs template and keep it in a shared
directory. Another idea is to give all of these fields a css class name
that is the same the use the select prototype call to do it in one fell
swoop using a collection proxy:

render :update do |page|’.notice_fields’).each do {|f| f.replace_html ‘’}

As long as all of the elements have class=“notice_fields” you are good
to go. Note that it can be any one of a number of classes for those
elements or any other valid css selector.


Thanks for the quick response Bill. I really appreciate it.

f.replace_html didn’t work since replace_html is not a Prototype Element
method, but I used Element.update instead. So the working syntax is:

render :update do |page|’.field_notice’).each { |f| f.update ‘’ }

Thanks again!

No problem. Sorry about the replace_html bit as I should have caught
that, but I was tired and headed to bed :slight_smile: Glad you got it to work.


mofo mofo wrote:


William P.