Search code examples
ruby-on-railsruby

How to trigger an action with select_tag without using the deprecated remote_function


I have an application that lists events. I want the user to be able to filter the events by category. In order to do this, I want to have a select box within which a user can select a category. When the user selects a category, I want an action to be triggered which will use JavaScript to list events from just that category. All Stack Overflow posts explaining how to do this use remote_function, which has apparently been discontinued. Right now, I have the code

select_tag "category",
    options_for_select(['Social', 'Academic','Sports and Recreation', 'Arts', 'Religious'])

How can I trigger an action with the select_tag when an option from the dropdown box is changed/selected? I'm guessing I may have to use the :onchangeoption, but I'm not sure how to do this.


Solution

  • stick this in the view, after the select tag:

    <script>
      $('#your_select_tag_id').on('change', function() {
        $.post({
          url: '/your/form/action',
          data: $('#your_form_id').serialize()
        }).success(function(data)) {
          console.log('this is what I got back: ' + data);
        };
      }
    </script>