Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - execute an ajax call via select dropdown menu

I have a view that contains a select tag, it is not part of a form just a stand alone drop down menu. On clicking one of the options I want to execute an ajax call

This is the select tag

<%= select_tag 'application_stage', options_for_select(application.job.hiring_procedure.hiring_procedure_stages.map{ |p| [p.name, p.id] }), prompt: "Hiring stage", class: 'input-block-level chzn-select hiring_stage_dropdown', id: 'hiring_stage_dropdown' %>

and this is a basic jquery through which I am trying to detect the change

    jQuery(function($) {
        console.log('clicked');
        $("#hiring_stage_dropdown").click(function() {
            var state = $('select#hiring_stage_dropdown :selected').val();
            console.log(state);
        });
    })

But when i select one of the options nothing happens, I know the ajax code is not there but all i want for now is to see something in console when one of the options is selected.

What am i missing here?

This is what the select looks like

<select class="input-block-level chzn-select hiring_stage_dropdown" id="hiring_stage_dropdown" name="application_stage">
  <option value="">Hiring stage</option>
  <option value="3">Manager Step 1</option>
  <option value="4">Manager Step 2</option>
</select>
like image 757
Saadia Avatar asked Oct 15 '25 18:10

Saadia


1 Answers

Executing an AJAX call when selecting an item from a select dropdown is built in to Rails via jquery-ujs.

First, make sure you have gem 'jquery-rails' in your Gemfile and //= require jquery_ujs in your application.js manifest file (they are both there by default).

Then add data-remote, data-url, and data-method attributes to your select. jquery-url will serialise the value of the select and make the request. Your select_tag code might look like:

<%= select_tag(
  'application_stage',
  options_for_select(
    application.job.hiring_procedure.hiring_procedure_stages.map{ |p| [p.name, p.id] }
  ),
  prompt: "Hiring stage",
  class: 'input-block-level chzn-select hiring_stage_dropdown',
  id: 'hiring_stage_dropdown',
  data: {
    remote: true,
    url: '/your_path',
    method: 'get'
  }
) %>

When a value is selected, jquery-ujs will make a GET request to /your_path?application_stage=:selected_value. You can then handle this in a js.erb response.

like image 190
Dom Christie Avatar answered Oct 17 '25 08:10

Dom Christie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!