Topic: [RJS] test if an element exists

i need to replace the html of my element. only i dont know if it exists.  sometimes it does, sometimes it doesnt.  i have this in my RJS file.

if page['my_id']
   page.replace_html 'my_id', 'my new markup'
end

even though there are no elements with the id of 'my_id' the line still fires.

any ideas?

Re: [RJS] test if an element exists

RJS is surprisingly limited when it comes to conditional stuff that relies on JS.  I'd recommend the "RJS minus R" plugin which allows you to do javascript directly.
http://www.danwebb.net/2006/11/17/rjs-minus-r
Then you can do the following:

page << 'if ($('my_id')) {'
page['a'].replace_html :partial => 'thing'
page << '} else {'
page['b'].replace_html :partial => 'thong'
page << '}'

Re: [RJS] test if an element exists

From my understanding the RJS minus R plugin will make your RJS look more like the RHTML views where you add the ruby generated javascript through ERB tags (<%= %>). Specifying JavaScript directly using page<< is how you would do it without the plugin.

Railscasts - Free Ruby on Rails Screencasts

Re: [RJS] test if an element exists

Also, using select to fetch the element with the id may work so you don't need to do a javascript "if" condition:

page.select("#my_id") { |e| e.replace_html 'my new markup' }

Untested.

Railscasts - Free Ruby on Rails Screencasts

Re: [RJS] test if an element exists

Oh, you're right ryan.  I just grabbed the sample code off the plugin page in a hurry.  It turns out it was used to describe what NOT to do.

Here's what you'd actually be doing:

if ($('my_id')) {
  $('a_certain_element').update(<%=js render(:partial => 'thing') %>);
} else {
  $('some_other_element').update(<%=js render(:partial => 'thong') %>);
}

Good catch Ryan.

Re: [RJS] test if an element exists

thanks for your help guys.

Re: [RJS] test if an element exists

Is it possible to achieve something like this?

if(page["elementid"]) then
     ruby_variable = true
else
    ruby_variable = false
end

is it possible combining ror-code with rjs in that way?

Last edited by Beakid (2007-09-04 06:15:47)