simonmorley
simonmorley

Reputation: 2804

Inserting Rails Variables into jquery

I've been following this guide about multiple jquery time span sliders. Am trying to get the daily start value from my rails app. Am struggling to get the variables to insert into the jquery function correctly.

I have a field for each day of the week which includes the start time (per day). Eg:

 @location.active_monday
 @location.active_tuesday
 @location.active_wednesday

The jquery function to display the sliders looks like this:

_sliderhtml: function(day){
            var displayday = day.charAt(0).toUpperCase() + day.substr(1);
            var html = ""+ 
                '<div class="fieldrow spacer">' +
                    '<div>' +
                      '<input type="text" name="location['+day+'_on_wifi]" id="'+day+'-time1" value="xxxxxxx" > - '+

In the input value, I'm trying to insert the value from my model but I can't figure out the correct syntax. Have tried:

 value="<%= "@location.active_wednesday" %>

Which works, but I need the day replaced with '+day+'. For example:

 value="<%= "@location.active_'+day+'" %>

Is there a way to do this or do I need to rethink?

Upvotes: 1

Views: 727

Answers (2)

Renato Zannon
Renato Zannon

Reputation: 29941

You need to rethink. You can't use your javascript variables (such as day, on your example) on ruby code, since it has already run. The values need to be on the rendered view if you need your javascript to be able to access it.

you can try something like this:

var active_values = {
  monday:    "<%= @location.active_monday %>",
  tuesday:   "<%= @location.active_tuesday %>",
  wednesday: "<%= @location.active_wednesday %>"
};

and then, on your JS function, just access the data:

'<input value="' + active_values[day] + '" />' ;

Upvotes: 5

digidigo
digidigo

Reputation: 2584

what you will need to do is assign a javascript location variable.

var location = <%= @location.to_json %>;

Then in your javascript method you can use.

value=location["active_" + day];

Upvotes: 1

Related Questions