0
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?

jQueryで名前入力フォームを実装。バリデーションとアラートの基本

Last updated at Posted at 2025-02-16
<form action="#" id="js-form-name" class="p-form">
  <div class="p-form__input">
    <input
      type="text"
      id="js-input-name"
      class="c-input"
      placeholder="山田 太郎"
    />
    <p class="p-form__error-message"></p>
  </div>
  <button type="submit" class="p-form__button c-form-button">送信</button>
</form>
jQuery("#js-form-name").on("submit", function (e) {
  e.preventDefault();

  const nameInput = jQuery("#js-input-name");
  const nameValue = nameInput.val();

  if (!nameValue) {
    nameInput.next(".p-form__error-message").text("名前を書いてね");
    return;
  }

  nameInput.next(".p-form__error-message").text("");
  alert(`${nameValue}さん、ようこそ`);
});
jQuery("#js-form-name").on("submit", function (e) {

#js-form-nameに対して、submitイベントを監視(バインド)する。
ユーザーがフォームの送信ボタンを押すと、この関数が実行される。

eは「イベント情報」を受け取るための変数で、“event”(イベント)の略。中身は「イベントオブジェクト」と呼ばれ、クリックや送信などの詳細な情報が入っている。

e.preventDefault();

デフォルトの送信動作を無効化する。通常、フォームが送信されるとページがリロードされるが、それを防ぐためにpreventDefault()を使う。

const nameInput = jQuery("#js-input-name");
const nameValue = nameInput.val();

#js-input-nameを取得し、nameInputに格納。
val()メソッドを使って入力された値をnameValueに格納。

if (!nameValue) {
  nameInput.next(".p-form__error-message").text("名前を書いてね");
  return;
}

nameValueが空(未入力)の場合は、エラーメッセージ「名前を書いてね」を表示して終了。
nameInput.next(.p-form__error-message)は、nameInputの直後にある兄弟要素でクラスが.p-form__error-messageの要素を取得し、そこにテキストをセットする。

nameInput.next(".p-form__error-message").text("");

ここまで来たということは、nameInputに値が入力されているので、エラーメッセージを消去する。

alert(`${nameValue}さん、ようこそ`);

入力された名前を使って、「◯◯さん、ようこそ」と表示。

0
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
0
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?