[RUBY] Initialize all values of [Rails] form with one click (helper method definition + JavaScript)

Postscript (2020/06/10)

With the method in this article, the only action you can achieve is form initialization (reset). How to make it completely clear (blank) is introduced in this article.

Notes created in advanced search form with [Rails] ransack

Introduction

While implementing a search form that allows you to add various search conditions, I wondered if there was a way to reset the search conditions with a single click.

As a result, I was able to implement it by the following method, so I will summarize it.

environment

procedure

To give a brief overview ** 1. Define a method to generate a reset button tag in the helper method ** ** 2. Call it in view ** ** 3. Write a process to clear the checkbox with js ** I feel like I will send it with three

1. Definition of helper method

Any file will do, but this time we will define it in helpers / application.rb.

helpers/application.rb


module ApplicationHelper
  def reset_tag(value = "Reset form", options = {})
    options = options.stringify_keys
    tag :input, { type: "reset", value: value }.update(options)
  end
end

2. Call in view file

ruby:search.html.haml


%div
  = reset_tag 'clear', id: 'js_clear_btn'
%div
  = f.submit 'Done'

Originally Rails does not have reset_tag, but since it is defined by a helper method, it can be called in this way.

Adjust with CSS and look like this ↓ スクリーンショット 2020-06-03 13.53.06.png

3. A description that clears the check box with JavaScript

In my case, I couldn't clear (uncheck) the checkbox with the reset button, so I wrote JavaScript there.

The code is highly environment dependent, so I'll omit it.

result

f923d6ccbb11ae2bb0c6d320371bc226.gif Like this, I was able to create a button that initializes all text_field, number_field, select, and checkbox!

reference

Use the button to initialize the form in Rails

Recommended Posts

Initialize all values of [Rails] form with one click (helper method definition + JavaScript)
Arguments with default values Take the full_title method of the Rails tutorial as an example
[Rails] devise helper method
definition of ruby method