0

How can I pass html object properties into embedded ruby code in an html.erb file?

Lets say I have a ruby method A that accepts a string parameter(and also the return value of A is string). I think of scenarios like the following:

<input type="text" id="t" value="Leaves">
<%= A(document.getElementById("t").value) %>

Obviously I can't write code that way.

I want to pass the value/text of the textbox into method A and print A's return value into the html body. How can I do that?

Also, if I want to continuously check the value of the textbox and append A's return value(when passed the current value of the textbox to A) to the body of the document, what should I do? And if I instead wanted to set some paragraph p's text to this return value, what should I have done?

1 Answer 1

1

You can use a HTML parser like Nokogiri.

frag = Nokogiri::HTML.fragment('<input type="text" id="t" value="Leaves">')
frag.at_css('#t').attr('value')

But it seems like a rather silly and overcomplicated solution to something that most likely can be solved by not using HTML strings to pass around data in your views / helpers in the first place.

Sign up to request clarification or add additional context in comments.

5 Comments

In the case of inputs you should be binding to a form builder object so I can't really see the need ever to do this. ERB templates are also not like the DOM. Its just a string buffer and you cant really just manipulate it as a document on the fly.
@max You are suggesting that I should use text_field_tag helper method, right? Then how can I retrieve the value of the created text field inside the embedded ruby code, either? (so that this value can be passed to the method A)
No i'm saying that you should be using form_for or form_with (Rails 5) which binds inputs to model instances. you should then use the f.text_field method of the form builder to create inputs. If you need the value you would use f.object.someproperty.
If you are creating the input you also know the value beforehand anyways so I can't see why you would need to parse it out of the html.
But i also get the feeling that you might not be getting the server/client flow and might be trying the oft repeated noob misstake of trying to handle client side changes to an input on the server.

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.