Force user to fill all fields before enabling form submit

前端 未结 12 2025
忘掉有多难
忘掉有多难 2021-02-07 00:49

I have a form containing various fields.

See jsFiddle demo.

My aim is to enable the submit button only when the user has filled in all fields.

So far,

12条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 01:55

    Thought I might chip in. Assuming as little as possible.

    jQuery("input, textarea").on("keyup click", function () { // going vanilla after easy-mode attach
        var sub = document.getElementById('subnewtide');
        if (require_all(find_form(this))) {
            sub.removeAttribute('disabled');
            sub.disabled = false;
        } else {
            sub.setAttribute('disabled', 'disabled');
            sub.disabled = true;
        }
    });
    
    function concat(a, b) { // concating Array-likes produces Array
        var slice = [].slice; // not assuming Array.prototype access
        return [].concat.call(
            slice.call(a, 0),
            slice.call(b, 0)
        );
    }
    
    function find_form(e) { // shim input.form
        if (e) do {
            if (e.tagName === 'FORM') return e;
        } while (e = e.parentNode);
        return null;
    }
    
    function require_all(form, dontIgnoreHidden) { // looks at textareas & inputs (excluding buttons)
        var inp = concat(form.getElementsByTagName('input'), form.getElementsByTagName('textarea')),
            rad = {}, // not assuming Object.create
            i, j,
            has = {}.hasOwnProperty; // not assuming Object.prototype access
        for (i = 0; i < inp.length; ++i) {
            switch ((inp[i].type || '').toLowerCase()) {
                default: // treat unknown like texts
                case 'text':
                    if (!inp[i].value) return false; break;
                case 'checkbox':
                    if (!inp[i].checked) return false; break;
                case 'radio':
                    j = inp[i].getAttribute('name');
                    if (!rad[j]) rad[j] = inp[i].checked;
                    break;
                case 'hidden':
                    if (dontIgnoreHidden && !inp[i].value) return false; break;
                case 'button':
                case 'submit':
                    break;
            }
        }
        for (j in rad) if (!has || has.call(rad, j)) // not assuming hasOwnProperty
            if (!rad[j]) return false;
        return true;
    }
    

提交回复
热议问题