Search code examples
javascripthtmlruby-on-railsruby-on-rails-3ruby-on-rails-plugins

Dynamically changing Ruby-on-Rails variables in a view


I have the following select_tag.

<%= select_tag :days, options_for_select(["Monday", "Tuesday"]) %>  

Somewhere, in the view I defined the following variable.

<% @day_of_week = "Monday" %>

And showed it :

<%= @day_of_week %>

I would like to dynamically change @day_of week, after a value is selected from the select_tag.


Solution

  • You can use jquery for this.

    Add this to the head of your html file (if you dont have jquery yet) :

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
    

    Wrap your text like this to give it an id :

    <div id="text_to_be_changed"><%= @day_of_week %></div>
    

    Give a specific id to your SELECT tab (if #days does not work for some reason).

    <%= select_tag :days, options_for_select(["Monday", "Tuesday"]), :id => "select_days" %>  
    

    Then add this unobtrusive JavaScript to the end of your view. Any change to the select#days will trigger a modification of div#text_to_be_changed's html.

    <script>
    $(document).ready(function(){
        $('#select_days').change(function() {
            $('#text_to_be_changed').html($(this).val());
        });
    });
    </script>