0

I have a collection of data in a select box, let's say @users = User.all. On change, I would like to get a variable in javascript with the user that is selected, I mean something like this :

    $("user_select").change(function(e){
        e.preventDefault();
        user_id = $(this).val();
        user = <%= @user.find(<user_id>) %>
    }) 

Is it possible? Or I have to put the whole collection in javascript variable and get it from there?

1
  • 1
    How about ajax request? Commented Jun 26, 2018 at 16:05

2 Answers 2

1

Is it possible?

Not like this, no. Your only two options are:

  1. server-side lookup: Make another request to the server, in which you pass user_id and retrieve user data.

  2. client-side lookup: As you mentioned, embed data from all users on the page and simply choose one of them, based on user_id.

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

1 Comment

Thank you Sergio!
1

I am thinking in a simple way, as @sergio-tulentsev said, what you are trying to do is not posble, but using more js, you don't need to find the user on the rails collection, if you already loaded all the users, then just past them to a javascript variable and on the change event, just select the one from there, something like this.

When you load your page with all the users, just save them on a javascript variable as json

var users = <%= @users.to_json.html_safe %>;

after that, on your event

$("user_select").change(function(e){
  e.preventDefault();
  user_id = $(this).val();
  $.each(users, function(i, u) {
    if (u.id == user_id) {
      user = u
      return;
    }
  });
}) 

with that you will have user with a json and all the values of the user there, you can then do something like user.name on javascript to get the values.

I used jquery because in you code example you are using it.

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.