워드프레스 댓글에서 이름과 내용을 입력해야 제출 버튼 활성화되도록 하기

Last Updated: 2023년 12월 27일 | | 15개 댓글

워드프레스 댓글 양식에서 이름 필드와 댓글 내용을 입력하지 않고 댓글 등록 버튼을 누르면 오류 페이지가 표시됩니다. 이름 필드와 댓글 내용을 작성하지 않으면 댓글 올리기 버튼이 눌러지지 않도록 하고 싶은 경우 아래의 방법을 사용할 수 있습니다.

워드프레스 댓글에서 이름과 댓글 내용을 입력해야 제출 버튼 활성화되도록 하기

이 블로그의 댓글 입력창에서는 이름과 댓글 내용을 모두 입력해야 댓글 등록 버튼이 활성화되도록 했습니다.

워드프레스 댓글에서 이름과 댓글 내용을 입력해야 제출 버튼 활성화하기

이름이나 댓글 내용 중 하나라도 입력하지 않으면 댓글 올리기 버튼이 비활성화되면서 댓글을 제출할 수 없게 됩니다.

GeneratePress 테마에서는 다음 코드로 댓글 작성자 이름과 댓글 내용을 모두 입력해야 댓글 등록 버튼을 활성화되도록 할 수 있습니다. 다른 워드프레스 테마에서는 테스트하지 않았지만 대부분 잘 작동할 것이라 생각됩니다.

CSS 코드:

/* Style for disabled submit button */
#submit:disabled {
    background-color: gray;
    color: white;
    cursor: not-allowed;
}

상기 CSS 코드를 차일드 테마 내의 스타일시트 파일(style.css)이나 워드프레스 관리자 페이지 » 외모 » 사용자 정의하기 » 추가 CSS에 추가할 수 있습니다.

자바스크립트 코드:

<script>
document.addEventListener('DOMContentLoaded', function () {
    const authorInput = document.getElementById('author');
    const commentInput = document.getElementById('comment');
    const submitButton = document.getElementById('submit');

    function updateButtonState() {
        if (authorInput.value.trim() !== '' && commentInput.value.trim() !== '') {
            submitButton.disabled = false;
        } else {
            submitButton.disabled = true;
        }
    }

    // Initial check
    updateButtonState();

    // Event listeners for input fields
    authorInput.addEventListener('input', updateButtonState);
    commentInput.addEventListener('input', updateButtonState);
});
</script>

상기 자바스크립트 코드를 "워드프레스에서 js 스크립트 파일과 스타일시트를 올바르게 로드하는 방법"을 참고하여 로드할 수 있습니다.

간단히는 그리 권장하지는 않지만 WPCode 플러그인을 설치하고 푸터 영역에 위의 코드를 추가할 수 있습니다.

GeneratePress 테마를 사용하는 경우에는 Elements에서 wp_footer 훅을 지정하여 푸터 영역에 코드를 추가할 수 있습니다.

댓글에 HTML 태그가 입력될 경우 오류 메시지 표시하기

이 블로그의 댓글 시스템에서 댓글을 작성할 때 HTML 태그를 입력하면 경고가 표시되면서 댓글 제출 버튼이 비활성화되도록 설정했습니다.

댓글에 HTML 태그가 입력될 경우 오류 메시지 표시하기

이름 필드와 댓글 내용을 입력하지 않으면 등록 버튼이 비활성화되고, HTML 태그가 댓글 내용에 포함될 경우 등록 버튼이 비활성화되고 경고 메시지가 표시되도록 하고 싶은 경우 다음 JavaScript 코드를 사용할 수 있습니다. (※ 2023년 12월 27일 업데이트: 처음 제시된 코드가 모바일에서는 작동하지 않아서 모바일에서 작동하도록 변경했습니다.)

<script>
window.addEventListener("DOMContentLoaded", function() { 
    // Find the textarea, author input, and submit button
    const textarea = document.querySelector('textarea[name="comment"][cols="45"][rows="8"]');
    const authorInput = document.getElementById('author');
    const submitButton = document.getElementById('submit');

    // Function to update the state of the submit button
    function updateSubmitButtonState() {
        const isAuthorNotEmpty = authorInput.value.trim() !== '';
        const isTextareaNotEmpty = textarea.value.trim() !== '';
        const hasHTMLTags = /<\/?[a-z][\s\S]*?>/i.test(textarea.value);

        submitButton.disabled = !(isAuthorNotEmpty && isTextareaNotEmpty) || hasHTMLTags;
    }

    if (textarea) {
        // Existing event listeners for the textarea
        textarea.addEventListener("input", handleTextareaInput);
        textarea.addEventListener("change", handleTextareaInput); // Added for mobile devices
    }

    if (authorInput) {
        // Event listener for author input field
        authorInput.addEventListener('input', updateSubmitButtonState);
        authorInput.addEventListener('change', updateSubmitButtonState); // Added for mobile devices
    }

    // Function to handle input and change events for textarea
    function handleTextareaInput() {
        const content = this.value;
        const hasHTMLTags = /<\/?[a-z][\s\S]*?>/i.test(content);
        let warning = document.getElementById("htmlTagWarning");

        if (hasHTMLTags) {
            if (!warning) {
                warning = document.createElement('span');
                warning.id = "htmlTagWarning";
                warning.className = "comments-warning";
                warning.innerHTML = 'Warning! HTML 태그 입력이 허용되지 않습니다. <a href="https://www.thewordcracker.com/lt-gt-converter/" target="_blank">여기</a>에서 부등호 기호를 변환하여 입력해주세요.';
                this.after(warning);
            }
        } else if (warning) {
            warning.remove();
        }

        updateSubmitButtonState();
    }

    // Initial check to update submit button state
    updateSubmitButtonState();
});
</script>

참고


15 개 댓글

Leave a Comment

  1. 댓글에 HTML 태그가 입력될 경우 오류 메시지 표시하는 JavaScript 코드가 WPCode 플러그인 푸터 영역에 추가하면 적용이 되는데 왜 Ad Inserter 플러그인 푸터 영역에 추가하면 적용이 안될까요?

    응답
    • 정확한 이유는 모르겠습니다만, 캐시 플러그인과 관련이 있지 않을까 생각되기도 하네요. Ad Inserter에서 작동하지 않으면 WPCode를 사용하시기 바랍니다.

      응답
  2. 댓글에서 이름과 내용을 입력해야 제출 버튼이 활성화 되도록 설정하면 굳이 이름 필드를 필수로 만들 필요가 없는 걸까요?

    응답
  3. 워드프레스에 로그인을 했을 때 제출 버튼이 항상 활성화 되어 있었던 거고 로그아웃을 하고 다시 확인해 보니까 비활성화가 되어 있네요^^

    응답
  4. 아래의 CSS 코드를 빼니까 적용되네요.

    /* 댓글 등록 버튼 스타일 변경 */

    input#submit.submit {
    background-color: #1e73be;
    padding: 7px 25px;
    border-radius: 30px;
    font-weight: bold;
    transition: background-color 0.3s ease;
    }

    input#submit.submit:hover {
    background-color: darkgray;
    }

    input#submit.submit:active {
    position: relative;
    top: 2px;
    }

    응답