0

I am new to rails. I have created a helper method with a loop. Inside the loop, I want to call a javascript function. Following is the code I have written. Any help would be appreciated. Helper method

def test_helper param1
   param1.each do |x|
     "js_function(x.col1, x.col2)"
   end
end

in javascript file test.js

function js_function(x1, x2){

}

1 Answer 1

1

Helper File:

def test_helper param1
  javascript_tag(
    param1.map do |x|
      "js_function(\"#{j raw(x.col1)}\", \"#{j raw(x.col2)})\";"
    end.join("\n")
  )
end

View File:

<%= test_helper SOMEPARAM %>

Will Render HTML (Something Like):

<script>
  js_function(SOMEVALUEA1, SOMEVALUEA2);
  js_function(SOMEVALUEB1, SOMEVALUEB2);
</script>
Sign up to request clarification or add additional context in comments.

22 Comments

Thanks, Jay. I am getting an error in browser console when I used your suggestion. <script type="text/javascript"> //<![CDATA[ //
Uncaught SyntaxError: Unexpected identifier <script type="text/javascript"> //<![CDATA[ //
Perhaps you might not need the outer <script>..</script> anymore. I'm updating my answer
If I don't specify javascript_tag the function is displaying as a string in browser console with &#x27;&#x27; for empty params. e.g., js_function((&#x27;&#x27;, &#x27;abc&#x27;);
What was the full error message? I just tried this on my sample rails project, and I did not get any error message on the browser.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.