Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RailsのJavascriptの記載場所

Last updated at Posted at 2023-06-10

導入

viewファイルにJSを以下のように記載することはあまりコードとしてよろしくないので、適切な箇所に記載するようにします。

form.html.erb
|
|
<script>
  document.addEventListener("DOMContentLoaded", () => {
    const todayButton = document.getElementById("today-button");
    const visitDayField = document.getElementById("content_visit_day");

    todayButton.addEventListener("click", () => {
      const today = new Date().toISOString().split("T")[0];
      visitDayField.value = today;
    });
  });
</script>

手順

JSのファイルを作成したのは、app/javascriptフォルダ内にしました。
このファイルに記述した内容は、どのViewでも使うことができます。

app/javascrip/script.js
document.addEventListener("DOMContentLoaded", () => {
  const todayButton = document.getElementById("today-button");
  const visitDayField = document.getElementById("content_visit_day");

  todayButton.addEventListener("click", (event) => {
    event.preventDefault();
    const today = new Date().toISOString().split("T")[0];
    visitDayField.value = today;
  });
});

※ここの記述は、フォームに「本日ボタン」を作るためのものです。

次にapp/javascript/packs/application.jsに上記で作成したファイルをimportしました。

app/javascrip/packs/application.js
import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"

import "script.js"

Rails.start()
Turbolinks.start()
ActiveStorage.start()

以上で、viewファイルにJSが動作すると思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Comments

No comments

Let's comment your feelings that are more than good

1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address