2

I have a JavaScript variable:

var selectValUser = $('.select_user :selected').val();

I need to use this variable in erb code on the same page, i.e

<%= get_free_hours_for_user(selectValUser) %>

How can I do it?

James Chevalier
  • 10,604
  • 5
  • 48
  • 74
Inaccessible
  • 1,560
  • 3
  • 18
  • 42

2 Answers2

7

You cannot do it because javascript run on client side while the code in ERB file runs at server side, you can send the value using ajax request, Plus here is an awsome rails cast

Here is an example to send message from javascript to controller; When user click on apply we have an action 'set_id' in controller, it get the power, do the validations etc, the show the message in 'id_message' div in views.

  $('#apply').live('click', function(event, data, status, xhr) {
    event.preventDefault();
    return $.ajax({
      url: '/users/registrations/set_id',
      type: 'GET',
      data: {
        code: $('#user_id').val()
      },
      success: function(data, event, status, xhr) {
        $('#id_message').html(response);
        return $("#id_message").show();
      },
      error: function(event, data, status, xhr) {
        $('#id_message').html(response);
        return $("#id_message").show();
      }
    });
  });

Hope it would answer your question

Muhamamd Awais
  • 2,385
  • 14
  • 25
  • but here i used nested form.i.e project has many tasks.for each task i should assign user.during allocation of user i should perform validation.for this validation i call helper method <%=get_free_hours_for_user(selectValUser)%> – Inaccessible Dec 29 '12 at 09:27
  • so you can return the data in 'selectValUser' as a string to controller and assign it to some instance variable and use it in view – Muhamamd Awais Dec 29 '12 at 09:31
2

There is no way to do it directly. Reason is, html runs in your server side whereas javascript runs in your local browser.

Additional discussion can be found here.

How to pass a javascript variable into a erb code in a js view?

And regarding different way to try it out, you can start with this.

http://jing.io/t/pass-javascript-variables-to-rails-controller.html

and

http://www.ruby-forum.com/topic/3818171

Community
  • 1
  • 1
LPD
  • 2,833
  • 2
  • 29
  • 48