javascript 送信ボタンの二度押しを防ぐ
- 作成日 2021.05.05
- 更新日 2022.08.19
- javascript
- javascript

javascriptで、送信ボタンの二度押しを防ぐサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.81
二度押し防止
「submit」時に、「disabled」に指定することで二度押しを防ぎます。
※コード内の「return false」は、画面遷移を防いで「disabled」を確認するためのもので実際に使用する場合は必要ありません。
<form id="frm" method="post" action="sample.php">
<input type="submit" id="btn" name="button1" value="送信する">
</form>
<script>
'use strict';
frm.onsubmit = function () {
btn.disabled = true;
return false; // 処理確認用
}
</script>
実行結果

サンプルコード
以下は、
「submit」ボタンをクリックして、「disabled」にして二度押しを防止する
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
window.onload = () => {
frm.onsubmit = () => {
console.log('1度しか実行されません');
btn.disabled = true;
return false; // 処理確認用
}
}
</script>
<body>
<div class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<form id="frm" method="post" action="sample.php">
<button id="btn" type="submit"
class="mt-5 bg-transparent border border-red-500 hover:border-red-300 text-red-500 hover:text-red-300 font-bold py-2 px-4 rounded-full">
submit
</button>
</form>
</div>
</div>
</body>
</html>
1度しか実行されていないことが確認できます。

「disabled」にする処理をコメントアウトすると、何度も実行できることが確認できると思います。
window.onload = () => {
frm.onsubmit = () => {
console.log('何度も実行されます');
//btn.disabled = true;
return false; // 処理確認用
}
}
実行結果

-
前の記事
go言語 スライス(配列)内の値をソートする 2021.05.04
-
次の記事
python python-docxを使ってWordファイルのテキストを取得する 2021.05.05
コメントを書く