1

I'm trying to do something: I have a event listener to call a function when a button is clicked (there is a dynamic amount of them), but I would like to pass an additionnal argument to the function depending, which would be a parameter defined in my controller.

Do you have any clue about how I could achieve that?

1 Answer 1

4

What you can do is set a data-* field in your html with the value from this "variable" set in the controller and inside the javascript function, get this.

For example, an .html.erb

<button id="my_id" data-myvalue="<%= $my_value %>">click me</button>

Javascript:

document.getElementById("my_id").onclick = function() {
console.log(this.getAttribute("data-myvalue"));
}
Sign up to request clarification or add additional context in comments.

1 Comment

Further to this, you must remember that Rails is a back-end infrastructure, meaning you can only "call" Rails data on your front-end if you explicitly set it at render time. To do this, you need to make sure you can set the Rails-centric data in your controller backend, to render in the view (IE - you cannot just "pass" Rails data to your browser -- it has to go through the view / HTML) To do this, you basically need to output the Rails data (from Chris' example the data attributes) to make sure your HTML view can output the required information

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.