2016-11-01 15 views
0

私のRailsアプリケーションでは、ユーザが左から右に移動するためにIPアドレスを割り当てる 'グループ'を選択できるところにselectドロップダウンがあります。選択肢に基づいて更新オプション

選択した特定のグループに既に割り当てられているIPアドレスを右手選択ボックス(hosts_assigned)に事前に入力できますか。グループを選択してもページがリロードされないので、Railsコントローラではできません。そのため、jQueryのものと仮定しています。

私はすでにRails MVCをセットアップしていますので、group.network_hostsを使用して、特定のグループに割り当てられたすべてのネットワークホストを取得できます。

enter image description here

ビューは、左から右にIPアドレスを移動できるように、いくつかのjQueryを使って、今非常に簡単です、そしてその逆:

<%= form_tag '/edit_host_group', id: 'edit_host_group_form', class: "form-horizontal form-label-left" do %> 
    <%= label_tag "Group", nil, required: true, class: "control-label col-md-2 col-sm-2 col-xs-12" %> 

    <%= select_tag "groups", options_from_collection_for_select(@host_groups, "id", "name"), include_blank: false, class: "form-control" %> 
    <%= label_tag "Available Hosts", nil, class: "control-label col-md-2 col-sm-2 col-xs-12" %> 

    <select id="hosts_available" class="form-control" size="30" multiple="multiple"> 
    <% @network_hosts.each do |n| %> 
     <% next if n.network_host_group_id %> 
     <option value="<%= n.id %>"><%= n.ip_address %></option> 
    <% end %> 
    </select> 

    <button type="button" id="btnRight" class="btn btn-success"><i class="fa fa-2x fa-forward"></i></button> 
    <br/> 
    <button type="button" id="btnLeft" class="btn btn-danger"><i class="fa fa-2x fa-backward"></i></button> 

    <select id="hosts_assigned" class="form-control" size="30" multiple="multiple"></select> 

    <%= text_field_tag :hosts %> 
    <%= submit_tag "Add Group", class: "btn btn-success" %> 
<% end %> 


<script> 
    function getHosts() { 
    var current_hosts=[]; 
    $("#hosts_assigned option").each(function() { 
     current_hosts.push($(this).val()); 
    }); 
    return current_hosts.length>0?current_hosts.join(","):""; 
    } 
    $("#btnLeft").click(function() { 
    $("#hosts_assigned option:selected").each(function() { 
     $("#hosts_available").append(this); 
    }) 
    $("#hosts").val(getHosts()); 
    }); 

    $("#btnRight").click(function() { 
    $("#hosts_available option:selected").each(function() { 
     $("#hosts_assigned").append(this); 
    }); 
    $("#hosts").val(getHosts()); 
    }); 
</script> 

答えて

1
  1. あなたがにハンドラを追加する必要がありますグループ選択タグのonChangeイベント。
  2. そのイベントハンドラでは、現在のグループIDを取得し、ajaxを実行してそのグループに割り当てられたIPのリストを取得します。 Ajaxはselectタグ全体または生データ(jsonリストのIP)を返すかもしれません。
  3. jQueryページのロードイベントでは、最初のグループのIPがロードされるようにonChangeイベントを手動でトリガーする必要があります。
  4. ユーザーが変更を加えたときに現在のhosts_assignedも保存する必要があります。再度ajaxを使用します。すでに定義したイベントハンドラ。
関連する問題