Putting a dynamic hash in JQuery using rails

140 Views Asked by At

I am newish to rails and new to JQuery. I am using jquery.timepicker with rails and it takes hashes to block out certain time ranges in a given list of times (ie, between 8am and 6pm, 1pm-2pm is not available). On a static page, the JQuery is written as so:

  <script>
    $('#someTextfieldPair .time').timepicker({
        'timeFormat': 'g:ia',
        'disableTimeRanges': [
          ['11:00am', '12:00pm'],
          ['3:00pm', '4:00pm']
        ]
     });
   </script>  

Instead of static times, I'm trying to create the hashes based on the values @other_events.time_start and @other_events.time_end. I've tried this, but I don't really know how to combine JQuery and rails.

 <script>
    $('#someTextfieldPair .time').timepicker({
        'timeFormat': 'g:ia',
        'disableTimeRanges': [
        <%= @other_events.each do |e| %>
          ['<%= e.time_start.strftime("%l:%M %P") %>', '<%= e.time_end.strftime("%l:%M %P") %>'],
          <%end %>
        ]
     });
   </script>  

I am using this jquery.timepicker: http://jonthornton.github.io/jquery-timepicker/

2

There are 2 best solutions below

2
On BEST ANSWER

I suggest you to check https://github.com/gazay/gon gem, it's fantastic for rails: it generates a javascript object on top of page, so you can access your time ranges (per page!) in javascript like you would do with any variable.

0
On

In helper.rb

def create_array(array_values)
   your logic......create your Hash or Array here
end

In your js file

<script>
    $('#someTextfieldPair .time').timepicker({
       'timeFormat': 'g:ia',
       'disableTimeRanges': $('#someTextfieldPair .time').after("#{escape_javascript create_array(@other_events)}")
   });
</script>