keyan.r
keyan.r

Reputation: 137

Updating link_to with a ruby on rails parameter using a select dropdown

My new school program path requires a school passed to it to denote which school is getting a new program. If there is no such school to pass, I added a dropdown that has all of the schools available so that someone can choose which school they want to add a program in. When this is selected, a javascript function triggers which adjusts the href of the button to the school value, however it is not working as I'd hoped. Here is the code:

<% if can? :create, @program %>
  <%= link_to 'New Program', new_school_program_path(@new_program_school), class: 'btn btn-primary', id: 'new-program-no-school' %>
  <%= select_tag(:menu_select, options_for_select(School.pluck(:name), School.all)) %>
  <br/>
<% end %>


<script>
  $('#menu_select').bind('change', function() { 
    var newLink = $('#menu_select').val();
    $('#new-program-no-school').attr('href', '<%= new_school_program_path(newLink) %>');
  });
</script>

Upvotes: 0

Views: 59

Answers (1)

Jonathan
Jonathan

Reputation: 945

This problem here is that Rails is rendering the javascript which is then executing independent of the Ruby code in the browser. The newLink variable is not available to Rails when it is rendering the path in the template.

You can do this to workaround that:

<script>
  $('#menu_select').bind('change', function() {
    var templatePath = '<%= new_school_program_path("school_id") %>'
    var newLink = $('#menu_select').val();
    $('#new-program-no-school').attr('href', templatePath.replace("school_id", newLink));
  });
</script>

Upvotes: 1

Related Questions