禁用“提交”按钮,除非选中该框

问题描述 投票:0回答:1

继我之前提出的问题之后 提交按钮不适用于 JS 验证

我一直在努力让复选框被选中作为表单验证的一部分。

我的html是

    <h1>Applicant Form</h1>
    <div class="container">
      <form action="create-lead.php" id="newLead" class="form" method="POST">
        <div class="form-field">
          <label for="firstName">First Name</label>
          <input type="text" name="firstName" id="firstName" id="firstName">
          <small></small>
        </div>
        <div class="form-field ">
          <label for="lastName">Last Name</label>
          <input type="text" name="lastName" id="lastName" id="lastName">
          <small></small>
        </div>
        <div class="form-field">
          <label for="email">Email</label>
          <input type="text" name="email" id="email">
          <small></small>
        </div>
        <div class="form-field">
          <label for="telephone">Telephone</label>
          <input type="text" name="telephone" id="telephone">
          <small></small>
        </div>
        <div class="form-field dropdown">
          <label for="buyerType" class="buyerType">Application Type</label>
          <select class="secondary" name="buyerType" id="buyerType">
            <option value="Purchase">Purchase</option>
            <option value="FirstTimeBuyer">First Time Buyer</option>
            <option value="Remortgage">Remortgage</option>
            <option value="RaiseFunds">Raise Funds</option>
          </select>
        </div>
        <div class="form-field">
          <label class="check-container" for="accept">
              <input class="check" type="checkbox" id="accept" name="accept" value="yes">
              I agree to the <a href="#">terms and conditions</a>
            </label>
          <small></small>
        </div>
        <div class="form-field buttons">
          <input class="submitButton" type="submit" name="submitButton" id="submitButton">
          <input class="clear" type="reset" name="reset" id="reset">
        </div>
      </form>
    </div>
    <script src="js/app.js"></script>
  

app.js 是

const firstNameEl = document.querySelector('#firstName');
const lastNameEl = document.querySelector('#lastName');
const emailEl = document.querySelector('#email');
const telephoneEl = document.querySelector('#telephone');
const checkedEl = document.getElementById('#accept');
const submitButton = document.getElementById('#submitButton');

const form = document.querySelector('#newLead');

const checkFirstName = () => {
    let valid = false;

    const firstName = firstNameEl.value.trim();

    if (!isRequired(firstName)) {
        showError(firstNameEl, 'First name cannot be left blank');
    } else if (!isFirstNameValid(firstName)) {
        showError(firstNameEl, 'First name must only contain letters');
    } else {
        showSuccess(firstNameEl);
        valid = true;
    };
    return valid;
};

const checkLastName = () => {
    let valid = false;

    const lastName = lastNameEl.value.trim();

    if (!isRequired(lastName)) {
        showError(lastNameEl, 'Last name cannot be left blank');
    } else if (!isLastNameValid(lastName)) {

        showError(lastNameEl, 'Last name must only contain letters');

    } else {
        showSuccess(lastNameEl);
        valid = true;
    }
    return valid;
};

const checkEmail = () => {
    let valid = false;
    const email = emailEl.value.trim();
    if (!isRequired(email)) {
        showError(emailEl, 'Email field cannot be left blank');
    } else if (!isEmailValid(email)) {
        showError(emailEl, 'Email is not valid')
    } else {
        showSuccess(emailEl);
        valid = true;
    }
    return valid;
};
const checkTelephone = () => {
    let valid = false;
    const telephone = telephoneEl.value.trim();
    if (!isRequired(telephone)) {
        showError(telephoneEl, 'Telephone field cannot be left blank');
    } else if (!isTelephoneValid(telephone)) {
        showError(telephoneEl, 'Number is not valid')
    } else {
        showSuccess(telephoneEl);
        valid = true;
    }
    return valid;
};

// const checkedElValid = () => {
//     if (!document.querySelector('#submitButton').checked) {
//         showError(, 'You must accept the terms to continue')
//     } else {
//         showSuccess(accept);
//         valid = true;
//     }
//     return valid;
// };

const isFirstNameValid = (firstName) => {
    const re = /^[a-zA-Z]+$/;
    return re.test(firstName);
};

const isLastNameValid = (lastName) => {
    const re = /^[a-zA-Z]+$/;
    return re.test(lastName);
};


const isEmailValid = (email) => {
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
};

const isTelephoneValid = (telephone) => {
    const re = /^[0-9]+$/;
    return re.test(telephone);
};

const isRequired = value => value === '' ? false : true;


const showError = (input, message) => {
    const formField = input.parentElement;
    formField.classList.remove('success');
    formField.classList.add('error');

    const error = formField.querySelector('small');
    error.textContent = message;
};

const showSuccess = (input) => {
    const formField = input.parentElement;

    formField.classList.remove('error');
    formField.classList.add('success');

    const error = formField.querySelector('small');
    error.textContent = '';
}


form.addEventListener('submit', function(e) {
    //validate fields
    let isFirstNameValid = checkFirstName(),
        isLastNameValid = checkLastName(),
        isEmailValid = checkEmail(),
        isTelephoneValid = checkTelephone();
        IsCheckedElValid = checkedElValid();


    let
        isFormValid = 
        isFirstNameValid &&
        isLastNameValid &&
        isEmailValid &&
        isTelephoneValid &&
        IsCheckedElValid;


    if (!isFormValid) {
        e.preventDefault();
        submitButton.disabled;
    } else {
        submitButton.disabled == false;

    };

});
// real time validation
const debounce = (fn, delay = 500) => {

    let timeoutId;

    return (...args) => {
        if (timeoutId) {
            clearTimeout(timeoutId);
        }
        timeoutId = setTimeout(() => {
            fn.apply(null, args)
        }, delay);
    };
};
//event delegation
form.addEventListener('input', debounce(function(e) {
    switch (e.target.id) {
        case 'firstName':
            checkFirstName();
            break;
        case 'lastName':
            checkLastName();
            break;
        case 'email':
            checkEmail();
            break;
        case 'telephone':
            checkTelephone();
            break;
    }
}));

我已包含注释掉的部分,因为这是我正在开发的功能,尝试将复选框包含为验证的一部分。

其他一切都很完美,但我需要确保用户接受条款和条件,然后才能发送表格。

似乎

e.preventDefault()
submitButton.disabled
没有按预期工作,除非我错过了一些东西..

我相对较新,没有经验使其正常工作!

编辑

根据https://stackoverflow.com/a/72778291/18227124

的建议

我正在将最终验证重写为

form.addEventListener("submit", function() {
    //validate fields
    let isFirstNameValid = checkFirstName(),
        isLastNameValid = checkLastName(),
        isEmailValid = checkEmail(),
        isTelephoneValid = checkTelephone();
    let
        isFormValid = 
        isFirstNameValid &&
        isLastNameValid &&
        isEmailValid &&
        isTelephoneValid;

    if (isFormValid) {
        let submitBtn = document.querySelector("button");
        let checkBox = document.getElementById("accept");

        checkBox.addEventListener("click", function () {
            if (checkBox.checked) {
               // submitBtn.disabled == false;
                submitBtn.disabled = false;
            } else {
               // submitBtn.disabled == true;
                submitBtn.disabled = true;
            }
        });
    };
    
});

但是,我认为我没有正确实施它

[编辑2年后] 在实现的解决方案中将比较运算符

==
更改为
=
,留下评论以显示我的愚蠢。

javascript forms preventdefault
1个回答
1
投票

您的代码太长且难以检查,但基本思想是在通过所有验证之前不要让用户单击提交按钮,而不是让他们单击提交然后查看一切是否有效。

因此,我们在复选框上设置了一个

click
事件处理程序,它只是根据复选框是否被选中来启用或禁用提交按钮。这样完成后,就不需要
preventDefault()

这是一个缩小的示例,您可以将其合并到代码中:

let submitBtn = document.querySelector("button");
document.querySelector("input").addEventListener("click", function(){
  if(this.checked){
    submitBtn.disabled = false;
  } else {
    submitBtn.disabled = true;
  }
});
<input type="checkbox"> I agree to the terms.
<button disabled>Submit</button>

© www.soinside.com 2019 - 2024. All rights reserved.