3
4

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.

スマホでHTML5のバリデーション時に該当箇所にスクロールしない問題への対処方法

Posted at

HTML5のフォームバリデーション、便利ですよね。

だけど、スマホだとエラー箇所にスクロールしてくれないんですよ。

色々探し回ってみたけど、jQueryでのバリデーションばっかりだったんですが、ピュアなJavaScriptでも結構簡単に解決できたのでここに残しておきます。

document.addEventListener("DOMContentLoaded", () => {
    const form = document.querySelector("form");
    form.addEventListener("submit", (event) => {
        const elements = form.elements;
        for (const element of elements) {
            if (!element.validity.valid) {
                element.scrollIntoView();
                element.reportValidity();
                return false;
            }
        }
    
        form.submit();
    });
});

HTML5のバリデーションはJavaScriptからは呼べないと勝手に思いこんでたんですが、ちゃんとできるんですね。

便利だなぁ。

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?