Search code examples
ruby-on-railsrjs

RJS: How to get the value and innerHTML of a DOM element


I want to assign the value and the innerHTML source of a DOM element to the local ruby variables. However, in my method seemly i can not make use of the RJS to complete this function. I don't know which method can implement it, in one words is: to assign a js variable value to a ruby local variable, how to do it ?

The limited situations are : page.assign only can assign a ruby variable value to a js variable. page[] only can get one DOM element object, can not return it's value or innerHTML


Solution

  • Are you saying you want to take the innerHTML of some element on the page via RJS, assign that to a Ruby variable, and use it in Ruby code in the RJS file? For example:

     # my_page.html
     <div id="foo">This is the content</div>
    

    and

    # my_page.js.rjs
    @some_var = page['foo'] # expecting to get "This is the content"
    do_something_amazing(@some_var)
    

    This is not possible in RJS. The reason is that your RJS code executes first on the server, and then sends its rendered results to the browser.

    If you need the contents of a DOM element to act upon on the server side, you'll need to send those contents to the server via a form post.