chinm3 chinm3 - 7 months ago 60
jQuery Question

Change label based on selected dropdown [Ruby on Rails 4.2]

I have a table called

it has the column

I use this
to get a list of all my network names:

<%= select_tag('NetworksList', options_from_collection_for_select(Network.all, :id, :name))%>

I also have 2 label fields that I want to populate with information dynamically:

<p>Network Type: <%= content_tag('span', "", id: 'NetworkType') %></p>
<p>Network Number: <%= content_tag('span', "", id: 'NetworkNumber') %></p>

When the user selects a network from the dropdown list of network names, I want to show the selected item's type and number in the fields named
. I would like this to render in the view immediately after the user selects a dropdown. How would I do this?


Put this Javascript in your app/assets/javascripts/network.js file:

$(document).ready(function() {
    $("#network_network_list").change(function() {
        var value = +$(this).val();
        var network_index = $.inArray(value, networks);
        var networkType = network_details[network_index][0];
        var networkNumber = network_details[network_index][1];

This will register an event handler that will act when the network selection is changed. The handler will get the new selected value and look up the value in the networks array, which will be used to pull the networkType and networkNumber from the corresponding position in the network_details array.

Now, at this point, networks and network_details haven't been defined, so you'll also need to include a snippet of Javascript in your view code to do that dynamically:

var networks = <%= raw( %>;
var network_details = <%= raw( {|network| [network.type, network.number] }.to_json) %>;

The Javascript code uses jQuery, so you'll need to make sure that jQuery is configured in the project. Check that these lines exist in the app/assets/javascripts/application.js file:

//= require jquery
//= require jquery_ujs

These lines include jQuery and jQuery UJS (unobtrusive Javascript) for the project, and these will be automatically included in the asset pipeline.