Search code examples
javascriptruby-on-railsajaxsimple-form

Uncaught TypeError: $(...)[0].reset is not a function


Goal

After a form is successfully submitted, I would like to reset the form to being empty.

Issue

After submitting the form, I get the following error message in my console:Uncaught TypeError: $(...)[0].reset is not a function

When I console.log my content before the reset I get the form: <div id=new-store-form>..</div>

What I've checked so far

  • In my application there are no id's, classes or anything else that are called "reset"
  • Pure javascript document.getElementById('new-store-form').reset(); gets me the same error message.

Code views/stores/index.html.erb

<div class="show-panel-form"></div>
  <%= render "partials/show_panel_stores_overview"%>
</div>

views/partials/show_panel_stores_overview.html.erb

<%= link_to 'New store', new_store_path, remote: true %>

views/stores/new.js.erb

var form = $("<%= j(render 'form') %>");
var wrapper = $('<div>').attr('id', 'new-store-form').append(form);
$('.show-panel-form').html(wrapper);

views/stores/_form

<%= simple_form_for (Store.new) do |f|%>
<%= f.input :name %>
<%= f.button :submit%>

views/stores.create.js.erb

var form = $("<%= j(render 'form') %>");
var wrapper = $('<div>').attr('id', 'new-store-form').append(form);
$('.show-panel-form').html(wrapper);
console.log($("#new-store-form")[0])
$("#new-store-form")[0].reset(); // doesn't work

store controller

def new
    @store = current_user.store.build
    @store.age_tables.build
    respond_to do |format|
      format.html { redirect_to root_url, alert: 'Page not accessible' }
      format.js
    end
    authorize @store

  end

  def create
    @store = current_user.stores.create(store_params)
    authorize @store
    if @store.save
      respond_to do |format|
        format.js
      end
    else
      format.js
    end
  end

Solution

  • Use a selector that matches the form, not the wrapper $('#new-store-form form').reset() (note the extra "form" to select the actual form tag inside the div)