Force user to fill all fields before enabling form

2020-05-30 06:56发布

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, I'm able to force the title field to have content before submit button is enabled. How do I make it so that all other fields need to be filled too before submit button is enabled.

    jQuery("input[type='text']").on("keyup", function () {
        if (jQuery(this).val() != "" ) {
            if (jQuery("#titlenewtide").val() != '')
            {
                jQuery("#subnewtide").removeAttr("disabled");
            }
        } else {
            jQuery("#subnewtide").attr("disabled", "disabled");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
        Title: <input id="titlenewtide" type="text" name="title" required> <br>
        Description: <textarea name="description" id="description"></textarea> <br>
        Tag:  <input id="newtag" type="text" name="newtag" required> <br>
        Category: <input type="radio" name="category" value="19" required> Animation
        <button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button> 
    </form>

Note that I am loading the JavaScripts in my footer.

12条回答
Explosion°爆炸
2楼-- · 2020-05-30 07:23
Use this html<br>
HTML:
<br>
<pre>
<form action="#" method="post" id="">
        Title: ##<input id="titlenewtide" type="text" name="title" required> 
        Description: <textarea name="description" id="description"></textarea>
        Tag:  <input id="newtag" type="text" name="newtag" required> 
        Category: <input type="checkbox" onclick="validate()" name="category" id="cate"value="19" required > Animation
        <button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>

</form>
</pre>
validation code:<br>
//on each key up function intiate the function validate
<pre>
    jQuery("input[type='text']").on("keyup", function () {
        validate();
    });
    jQuery("#description").on("keyup", function () {
        validate();
    });

    function validate(){
     jQuery("input[type='text']").each(function(){

        if (jQuery(this).val() != "" )
        {
            if((jQuery("#description").val() !="") && (jQuery("#cate").is(':checked')))
            {

                jQuery("#subnewtide").removeAttr("disabled"); 
            }
            else {
                jQuery("#subnewtide").attr("disabled", "disabled");
            }
        } 
    });
    }
    </pre>
    you can find the fiddle in : https://jsfiddle.net/s8uv2gkp/
查看更多
萌系小妹纸
3楼-- · 2020-05-30 07:24

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;
}
查看更多
▲ chillily
4楼-- · 2020-05-30 07:25

Why don't you use jquery validate . It's a good plugin .

The logic works like, any change in the form it will check the form is valid or not. And also using the errorplacement function it will disable the default error message also.

$().ready(function() {
    // validate signup form on keyup and submit
    $("#contactForm").validate({
        rules: {
            title: "required",
            description: {
                required: true
            },
            newtag: {
                required: true
            },
            category: {
                required: true
            }
        },
        errorPlacement: function(error, element) {
            return true;
        },
        submitHandler: function() {


        }
    });


    $('#contactForm').change(function() {
        if ($("#contactForm").valid()) {
            $("#subnewtide").removeAttr("disabled");
        }
    });

});

Fiddle

查看更多
Melony?
5楼-- · 2020-05-30 07:29

Here's how you can do it:

$(document).ready(function () {
    var $inputs = $("#new_tide input:not([type=hidden]), #new_tide textarea");

    $inputs.on("input change", function () {
        valid = true;
        $inputs.each(function () {
            valid *= this.type == "radio" ? this.checked : this.value != "";
            return valid;
        });    
        $("#subnewtide").prop("disabled", !valid);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
    Title: <input id="titlenewtide" type="text" name="title" required> <br>
    Description: <textarea name="description" id="description"></textarea> <br>
    Tag:  <input id="newtag" type="text" name="newtag" required> <br>
    Category: <input type="radio" name="category" value="19" required> Animation
    Hidden: <input type="hidden">
    <button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button> 
</form>

查看更多
Emotional °昔
6楼-- · 2020-05-30 07:29

By far the easiest, would be to rely on the HTML5 validation you're already using.

You'd have to add required to all form controls if you want to require all of them, and that can easily be done by using jQuery's :input selector and setting the property, like so

$(':input:not(#subnewtide)').prop('required', true)

We'll exclude the submit button, as that doesn't have to be required, obviously, not that it would matter in this case.

Then we'll listen for the input event, which covers all sorts of inputs, like typing, pasting etc, and the change event as well to cover the radio button.

Using form.checkValidity() tells us if the form is valid, and returns a boolean, so we could use it directly to set the disabled property of the submit button.

All together it looks like this, and that's all you need, a few lines of really simple code

$(':input:not(#subnewtide)').prop('required', true).on('input change', function() {
    $('#subnewtide').prop( 'disabled', !this.form.checkValidity() );
});

FIDDLE

If you have to support old browsers that don't have HTML5 validation, you can use the H5F polyfill

查看更多
孤傲高冷的网名
7楼-- · 2020-05-30 07:34

There's actually a pretty easy approach. I'm using native JavaScript, but I think it is applicable in jQuery as well:

var form = document.getElementById("new_tide");
form.onchange = function onChange() {
    var enable = true;
    var inputs = form.getElementsByTagName("input");
    var textareas = form.getElementsByTagName("textarea");

    for (var i in inputs) {
        enable = enable && inputs[i].value != "";
    }

    for (var i in textareas) {
        enable = enable && textareas[i].value != "";
    }

    enable = enable && textarea.value != "";
    document.getElementById("subnewtide").disabled = !enable;
}

The change event on form is always called, when any input or textarea element was changed (click in element, type, click somewhere else or lose focus).

Edit:
Regarding hidden fields, you can exclude them by surrounding the enable calculation with an if-condition:

if (!inputs[i].hidden) {
    enable = enable && inputs[i].value != "";
}

Note:
This will work in any browser (even Internet Explorer 5.5). Check on MDN:

for ..in Loop
element.getElementsByTagName()
document.getElementById()

查看更多
登录 后发表回答