0

In my edit.html.erb I'm using some javascript mixed with some ruby code:

var sel = document.getElementById("right").;
        var len = sel.options.length;
        var str = "";
        for (var i = 0; i < len; i++) 
                {
                if(sel.options[i].selected) 
                    {
                    <% RHoliday.find_or_create(holiday_id: sel.options[i].value , group_id: @group.id ) %> 
                    }
                }

        }

But I always get the following error:

undefined local variable or method `sel' for #<#:0x3f90ee8>

It's because I'm trying to access a variable from my javascript. My question is: Is there a way to get around this error?

1
  • Where do you assign the value to the document which ID is "right"? Commented Mar 28, 2014 at 13:18

1 Answer 1

2

Short answer: You can't do this, JavaScript is client side, Ruby is server side.

Long answer:

You need to make an ajax call in your javascript rather than writing ruby explicitly into the function.

var sel = document.getElementById("right").;
var len = sel.options.length;
var str = "";
for (var i = 0; i < len; i++) 
{
  if(sel.options[i].selected) 
  {
    $.ajax("/holiday/create", {holiday_id: sel.options[i].value, group_id: @group.id}).done(function(data){
      //do something with data here
    });
  }
}

Then set up your routes and in your holiday controller:

def create
  render json: RHoliday.find_or_create(holiday_id: params[:holiday_id].to_s, group_id: params[:group_id].to_s)    
end

Don't suggest you use this exact code, but it gives you a starting point

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.