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

5
  • 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. Commented Nov 8, 2022 at 18:29
  • @DaveNewton I am actually new to Rails. Can you guide a little on how to proceed? Thanks. Commented Nov 8, 2022 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. Commented Nov 8, 2022 at 18:43
  • Duplicated from this: stackoverflow.com/questions/2721880/… stackoverflow.com/questions/2464966/… Commented Nov 8, 2022 at 19:02
  • 1
    Does this answer your question? How to pass Ruby variables to a JavaScript function in a Rails view? Commented Nov 8, 2022 at 19:02

1 Answer 1

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});" %>"/>
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Gilmore! Are you sure it will work for objects too? As I am still getting Invalid or unexpected token.
are a,b,c Hash?, if so it will not working. we need to .to_json.html first

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.