jQuery disable/enable submit button

后端 未结 21 3121
难免孤独
难免孤独 2020-11-22 07:30

I have this HTML:



How can I do something li

21条回答
  •  旧时难觅i
    2020-11-22 07:54

    Vanilla JS Solution. It works for a whole form not only one input.

    In question selected JavaScript tag.

    HTML Form:

    var form = document.querySelector('form')
        var inputs = form.querySelectorAll('input')
        var required_inputs = form.querySelectorAll('input[required]')
        var register = document.querySelector('input[type="submit"]')
        form.addEventListener('keyup', function(e) {
            var disabled = false
            inputs.forEach(function(input, index) {
                if (input.value === '' || !input.value.replace(/\s/g, '').length) {
                    disabled = true
                }
            })
            if (disabled) {
                register.setAttribute('disabled', 'disabled')
            } else {
                register.removeAttribute('disabled')
            }
        })

    Some explanation:

    In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.

    If you need to disable submit button until all required input fields are filled in - replace:

    inputs.forEach(function(input, index) {
    

    with:

    required_inputs.forEach(function(input, index) {
    

    where required_inputs is already declared array containing only required input fields.

提交回复
热议问题