0

I'm trying to do something very simple, but I can't figure out. How can I access a local JavaScript variable in Ruby? Or, if that's not possible, can I find an element on the page by its name or id? I'm trying to fit it into the following:

inp = document.getElementById("email").value; 

<% if User.pluck(:email).include? **JAVASCRIPT VARIABLE "INP"** then %>
alert("found")
<% end %>

Thanks.

3
  • 5
    Ruby only runs on the server...long before javascript runs in the browser. Neither knows anything about the other Commented Jan 29, 2018 at 22:04
  • So can I find an element by its Id or name? Commented Jan 29, 2018 at 22:08
  • 2
    You need JavaScript to send data back to Ruby via AJAX or a regular request. Once you've rendered the page Ruby is done, no longer involved, and it's up to the browser to take over. Commented Jan 29, 2018 at 22:14

1 Answer 1

0

I don't think its possible as Ruby is executed server side and javascript is client side language. But you can use ajax to pass client side variable(JS) to server and tackle this situation.

For Example - using little JS you can pass client side variable to server side and get the result.

var email = $('#email').val();
$.post('/email_lookup?email='+email,function(data){
  console.log(data);
});

In Controller, you can define an action which will look for provided email and return a json data whether the email exists or not.

def email_lookup
  @user = User.where(email: params[:email]).try(:first)
  render json: {
    email_found: @user.present?
  }
end
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.