Godzilla74 Godzilla74 - 1 year ago 86
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


Here's what the form looks like

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 %>

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

var selectedItem = $("#hosts_assigned option:selected");

var selectedItem = $("#hosts_available option:selected");

In my controller for loading the view

class SettingsController < ApplicationController
before_action :get_company_and_locations

def global


The POST action is calling
, 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}"


And my routes are:

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

Answer Source

Button elements default to submit

Add a type of button

<button type="button" id="btnRight" class="btn btn-success">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download