Reputation: 202
I have a ruby value that is referred to as <%= @random_quote.quote %>
which outputs a string, and I would like to set this string equal to the javascript value in document.getElementById("quoteArea").value = "value"
. I have looked around here and found similar questions but none of them solve my problem. Any ideas? Thanks.
Upvotes: 2
Views: 1700
Reputation: 4440
Check out the gon gem If you need to send some data to your js files and you don't want to do this with long way through views and parsing.
This assigns values to variables that will be accessed through javascript
gon.variable_name = variable_value
# or new syntax
gon.push({
:user_id => 1,
:user_role => "admin"
})
gon.push(any_object) # any_object with respond_to? :each_pair
Then to access that variable in javascript do:
gon.variable_name
In the JS file.
Upvotes: 0
Reputation: 411
You can make a file.js.erb The files are interpreted first by ruby then by js.
var jsVariable = "<%=ruby_variable%>";
Upvotes: 0
Reputation: 1489
You can use some.js.erb in your assets pipeline and assign the value from there, not a very good approach but one way to go, or you can set the value in DOM( Document Object Model ) in certain element data and get the value from there. As follows an dummy example.
<div data-my_value="<%= @random_quote.quote %>"></div>
jQuery("[data-my_value]").data("my_value");
Some thing like that. Hope this helps you.
Cheers
Upvotes: 2
Reputation: 54882
If you are using erb for your views:
# your_view.html.erb
document.getElementById("quoteArea").value = "<%= @random_quote.quote %>";
If you are using HAML for your views:
# your_view.html.haml
:javascript
document.getElementById("quoteArea").value = "#{@random_quote.quote}";
Upvotes: 3
Reputation: 7449
Assign that Ruby value to a JavaScript variable.
Something like:
var myVariable = "<%= @random_quote.quote %>";
document.getElementById("quoteArea").value = myVariable;
Upvotes: 0
Reputation: 574
If the element with the id #quoteArea
is available in your view, you should be able to set it's value using the same erb code you referenced in your question.
If you do not have any control over the #quoteArea
element, you can define a javascript variable in your page that you can then use later:
// In Your HTML View
<script>
var quote = "<%= @random_quote.quote %>";
</script>
// In a JS File loaded after the variable assignment
document.getElementById("quoteArea").value = quote;
Upvotes: 0