Godzilla74 Godzilla74 - 1 month ago 5
jQuery Question

Rails javascript buttons causing post

I've created a form where a user can move items from the left side to the right side using two buttons. After the user has finished adding their items they can name & save the group. At least that's how it's supposed to work. Instead, as soon as I add one item, and click on the 'move right' button the POST action fires. Why are my javascript driven buttons firing the POST action instead of the

submit_tag
?

Here's what the form looks like
view/settings/global.html.erb
:

enter image description here

The form code in the view:

<%= form_tag '/create_host_group', id: "host_group_form", class: "form-horizontal" do %>

<%= label_tag "Group Name", nil, required: true, class: "control-label col-md-2 col-sm-2 col-xs-12" %>
<%= text_field_tag 'host_group_name', nil, 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>
<% @network_hosts.each do |n| %>
<option value="<%= n.id %>"><%= n.ip_address %></option>
<% end %>
</select>

<button id="btnRight" class="btn btn-success"><i class="fa fa-2x fa-forward"></i></button>
<br/>
<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></select>

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

<script>
$("#btnLeft").click(function(){
var selectedItem = $("#hosts_assigned option:selected");
$("#hosts_available").append(selectedItem);
});

$("#btnRight").click(function(){
var selectedItem = $("#hosts_available option:selected");
$("#hosts_assigned").append(selectedItem);
});
</script>


In my controller for loading the view
settings_controller.rb
:

class SettingsController < ApplicationController
before_action :get_company_and_locations

def global
get_network_hosts
end

end


The POST action is calling
network_host_groups_controller#create
, which I'm just trying to debug right now:

class NetworkHostGroupsController < ApplicationController

def create
group_name = params[:host_group_name]
assigned_hosts = params[:hosts_assigned]
puts "#{group_name}: #{assigned_hosts}"
end

end


And my routes are:

match '/global_settings', to: 'settings#global', via: 'get'
match '/create_host_group', to: 'network_host_groups#create', via: 'post'

Answer

Button elements default to submit

Add a type of button

<button type="button" id="btnRight" class="btn btn-success">
Comments