views:

676

answers:

3

Is it possible to change a html tag attribute value from an RSJ template? I know that there is a page.replace_html method, but it is not very useful in my case, since I have lengthy values of various attributes (such as alt, title of an image). What I want is change src attribute of a img tag in RJS. Is that possible at all?

Thank you.

+3  A: 

EDIT: My first attempt didn't work, but this one does.

update_page do |page|
  page['image_id']['src'] = new_image_url
end
Can Berk Güder
You're welcome. =)
Can Berk Güder
+3  A: 

Slight modification to Can's answer. As suggested,

update_page do |page|
    page['image_id']['src'] = new_image_url
end

translates to JS:

$('image_id').src = new_image_url

This will work for some attributes that have direct JS DOM variable access, many don't. Luckily RJS is pretty good at rewriting JS method calls:

update_page do |page|
    page['image_id'].set_attribute('attrib', new_attrib_val)
end

translates to JS:

$('image_id').setAttribute('attrib', new_attrib_val)

and you should be good to go.


Small update: you may want to use write_attribute instead if you want IE compatibility.


Small update: in the above, [:src] and :attrib would probably be better style if these are static.

Chinasaur
A: 

Depending on the Rails setup, the code above might work only if you exclude the page_update start and end lines -- I'm running Rails on mongrel on Windows 7, and putting the page[element][attribute] code on its own, outside of the update_page block, works fine, but including it inside the block breaks the code.

jatkins