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

1 minute read

Addition (2020/06/10)

With the method in this article, the action that can be achieved is form initialization (reset). This article introduces how to completely clear (blank).

Memo writing of detailed search form in [Rails]ransack

Introduction

While implementing a search form with various search conditions, I wondered if there was a way to reset the search conditions with one click.

As a result, I implemented it by the following method, so I will summarize it.

environment

  • Ruby 2.5.1
  • Rails 5.2.4

procedure

To briefly explain the outline, 1. Define a method to generate reset button tag in helper method 2. Call it on the view 3. Write a process to clear the check box with js I feel like I will send it in three

1. Definition of helper method

You can use any file, but this time 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 there is no reset_tag in Rails, but since it was defined in a helper method, it can be called with this syntax.

Adjust with CSS as well ↓  Screenshot 2020-06-03 13.53.06.png

3. Description to clear the check box in JavaScript

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

I will omit the code because it depends heavily on the environment.

result

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

reference

Use a button to initialize the form with Rails