2

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.

0

6 Answers 6

3

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

1 Comment

Thanks! Worked perfectly.
2

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

Comments

0

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;

Comments

0

Assign that Ruby value to a JavaScript variable.

Something like:

var myVariable = "<%= @random_quote.quote %>";

document.getElementById("quoteArea").value = myVariable;

Comments

0

You can make a file.js.erb The files are interpreted first by ruby then by js.

var jsVariable = "<%=ruby_variable%>";

Comments

0

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.

Comments

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.