Code & Clay – Notes to self. Mainly Ruby/Rails.

Submitting a form properly when using javascript

I have a search form in a view.

<%= form_with url: issues_path, class: 'filter-box' do %>
  <%= text_field_tag(:filter_by, '', id: 'filter-text-field') %>
<% end %>

When the form is submitted, the following action is run:

class IssuesController < ApplicationController

  def create
    @labels = Label.by_search_term(params[:filter_by])
    respond_to do |format|

All works well.

However, I want the action to be triggered with every keystroke. To that end, I have added the following javascript.

  document.getElementById('filter-text-field').addEventListener('keyup', function(){

But when the form is submitted on key up it breaks and I get an error:

ActionController::UnknownFormat in IssuesController#create.

The problem is that no format is specified in the request when the javascript submits the form.

The solution is to use Rails’s own javascript helper

      document.getElementById('filter-text-field').addEventListener('keyup', function(){, 'submit')

It’s implemented here and here.