Neo Teo Neo Teo - 5 months ago 13
Javascript Question

how to change view's vairable in js of rails

how to change view's variable value in javascript. I mean when i select April from dropdown table will show only April's data and current table data will disappear and refreshed. How can i do it? Help me


My JS

:javascript
var updateMonth = function(){
var month_id = $("#select_other_month").val();
console.log(month_id)
}


here is my select tag (dropdown)

%select{:name => "options", :id=>"select_other_month",:onchange=>"updateMonth()"}
%option.placeholder{:disabled => "", :selected => "", :value => ""} see other months
%option{:value => "0"} this month
-a=@this_month - 1.month
%option{:value => "5"}=a.strftime('%Y-%m')
-b=@this_month - 2.month
%option{:value => "4"}=b.strftime('%Y-%m')
-c=@this_month - 3.month
%option{:value => "3"}=c.strftime('%Y-%m')
-d=@this_month - 4.month
%option{:value => "2"}=d.strftime('%Y-%m')
-e=@this_month - 5.month
%option{:value => "1"}=e.strftime('%Y-%m')


and my table looks like this

.table{:id=>"time_table"}
%table{:border=>"1"}
%thead
%tr
%th No
%th Name
-(@xmonth.at_beginning_of_month..@xmonth.at_end_of_month).each do |day|
-if (day.saturday? || day.sunday?)==false
%th=day.strftime("%d")
%th Total days
%th Total time


I want change my @xmonth vairable from JS


Note: @this_month = Date.today

Answer
var updateMonth = function(){
  var month_id = $("#select_other_month").val();
  $.ajax({
    url: '/your_controller/its_method', //make sure to add this path to routes file
    data: {
      month_id: month_id
    },
    success: function(response){
      $("#target_area").html(response);
    },
    error: function(error_res){
      console.log(error_res);
    }
  });
}

In your view file add an id, so we can replace its content with the new response we get

%thead{:id => "target_area"}
  %tr
    %th No
    %th Name
    ...

In your controller

class YourController
   def your_method
     month_id = params[:month_id]
     #update your @xmonth by month_id
     #your new information should be inside @xmonth object
     respond_to do |format|
       format.html {render partial: 'your_controller/your_method/your_partial.haml.erb' }
     end
   end
end

Create your partial file _your_partial.haml.erb with the content that needs to be replaced

%tr
  %th No
  %th Name
  -(@xmonth.at_beginning_of_month..@xmonth.at_end_of_month).each do |day|
    -if (day.saturday? || day.sunday?)==false
  %th=day.strftime("%d")
  %th Total days
  %th Total time

The partial's content will be replaced in your view with the content of #target_area when you get a success response. See the updateMonth function.

Hope this helps

Comments