Reputation: 2502
In my Rails app I have a select
drop down where the user can select a 'group' that they would then assign IP addresses to moving them from left to right.
How can I pre-populate the right hand select box (hosts_assigned
) with the IP addresses that have already been assigned to a specific group that's selected? I can't do it through my Rails controller since selecting the group doesn't reload the page, so I'm assuming it would be a jQuery thing.
I've already setup the Rails MVC, so I can just use group.network_hosts
to get all network hosts assigned to a given group.
The view is pretty simple right now, with some jQuery to allow moving IPs from left to right, and vice-versa:
<%= 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>
Upvotes: 0
Views: 40
Reputation: 81
Upvotes: 1