R0bur
R0bur

Reputation: 57

Get rails variables as parameter to an onclick event function

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?

Upvotes: 1

Views: 4142

Answers (1)

Christian Benseler
Christian Benseler

Reputation: 8065

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"));
}

Upvotes: 4

Related Questions