フォームMessege欄に「http」が入っていた場合フォーム送信ボタンを無効化する方法(営業連絡防止)
<script>
(function() {
// --- ▼ 設定項目 ▼ ---
// メッセージ入力欄に設定したID
const MESSAGE_FIELD_ID = 'message-field';
// 送信ボタンに設定したID
const SUBMIT_BUTTON_ID = 'submit-button';
// URL検出時にボタンに表示するテキスト
const DISABLED_BUTTON_TEXT = 'フォームにURLリンクがあるため送付できません';
// --- ▲ 設定項目 ▲ ---
// この変数に、ボタンの元のテキストを保存します
let originalButtonText = '';
function setupUrlBlocker() {
const messageField = document.getElementById(MESSAGE_FIELD_ID);
const submitButton = document.getElementById(SUBMIT_BUTTON_ID);
if (!messageField || !submitButton) {
return false; // 要素が見つからない場合は再試行
}
// ★★★★★ 修正点 ★★★★★
// ボタン内部の<p>タグを直接探し、なければボタン自体を対象とする
const textElement = submitButton.querySelector('p') || submitButton;
// 実際のボタンのテキストを読み取って保存する
originalButtonText = textElement.textContent;
console.log('✅ ボタンの元のテキストを取得しました:', originalButtonText);
console.log('✅ URLブロック機能の監視を開始しました。');
messageField.addEventListener('input', function() {
const hasUrl = messageField.value.toLowerCase().includes('http');
if (hasUrl) {
//【URLが見つかった場合】
textElement.textContent = DISABLED_BUTTON_TEXT; // テキスト要素を直接書き換え
submitButton.disabled = true;
submitButton.style.opacity = '0.5';
submitButton.style.cursor = 'not-allowed';
} else {
//【URLが見つからない場合】
textElement.textContent = originalButtonText; // 保存しておいた元のテキストに戻す
submitButton.disabled = false;
submitButton.style.opacity = '1';
submitButton.style.cursor = 'pointer';
}
});
// 初回チェックを実行
messageField.dispatchEvent(new Event('input'));
return true;
}
const observer = new MutationObserver(function() {
if (setupUrlBlocker()) {
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
})();
</script>// メッセージ入力欄に設定したID
const MESSAGE_FIELD_ID = 'message-field';
// 送信ボタンに設定したID
const SUBMIT_BUTTON_ID = 'submit-button';
この部分は適宜差し替えてください。