Force user to fill all fields before enabling form submit

前端 未结 12 2026
忘掉有多难
忘掉有多难 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:35

    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()

提交回复
热议问题