0

Edit: a, b, c are objects.

I have an erb file as follows with a, b, c variables.

<script type="text/javascript">
  function fun(a,b,c){
    console.log(a);
    console.log(b);
    console.log(c);
  }
</script
<% a %>
<% b %>
<% c %>
<input type="checkbox" id="group_box" onclick="fun(a,b,c);"/>

But either the variable gets passed as string or it throws Invalid or Unexpected token error.

What am I doing wrong?

This is all I have tried so far -

  1. onclick = "fun(a, b, c)"
  2. onclick = "fun('a, b, c')"
  3. onclick = "fun(\'' + a + '\', \'' + b + '\', \'' + c + '\')"
  4. onclick = "fun(\'' + <%= a %> + '\', \'' + <%= b %> + '\', \'' + <%= c %> + '\')"

TIA

Surbhi Goel
  • 15
  • 1
  • 8
  • 1
    Rails views run on the server, JS runs in the browser. You can render Rails data into views several ways; the first step is to get it into the JS at all. – Dave Newton Nov 08 '22 at 18:29
  • @DaveNewton I am actually new to Rails. Can you guide a little on how to proceed? Thanks. – Surbhi Goel Nov 08 '22 at 18:33
  • 1
    `const a = <%= a %>; function fun(a, b, c) { ... };` with the caveat that the value needs to be JS-escaped/-quoted. Or you can render JSON, etc. There's several options--try #4 was the closest, but you need to look at the rendered output to see what may have gone wrong. It also matters how the data is being passed to the view layer, e.g., instance variables like `@a` or some other mechanism. – Dave Newton Nov 08 '22 at 18:43
  • Duplicated from this: https://stackoverflow.com/questions/2721880/ruby-on-rails-send-javascript-variable-from-controller-to-external-javascript https://stackoverflow.com/questions/2464966/how-to-pass-ruby-variables-to-a-javascript-function-in-a-rails-view – Pedro Augusto Ramalho Duarte Nov 08 '22 at 19:02
  • 1
    Does this answer your question? [How to pass Ruby variables to a JavaScript function in a Rails view?](https://stackoverflow.com/questions/2464966/how-to-pass-ruby-variables-to-a-javascript-function-in-a-rails-view) – Pedro Augusto Ramalho Duarte Nov 08 '22 at 19:02

1 Answers1

1

you must first wrap the whole string function using erb then do interpolation to call those variables.

<% a = 1 %>
<% b = 2 %>
<% c = 3 %>
<input type="checkbox" id="group_box" onclick="<%= "fun(#{a},#{b},#{c});" %>"/>

the result will be this

<input type="checkbox" id="group_box" onclick="fun(1,2,3);"/> 

if your a,b,c variables are Hash and you want to pass object to fun function, then you need to convert it to json first.

<% a = a.to_json.html_safe %>
<% b = b.to_json.html_safe %>
<% c = c.to_json.html_safe %>
<input type="checkbox" id="group_box" onclick="<%= "fun(#{a},#{b},#{c});" %>"/>