Check all elements in form with Javascript

前端 未结 4 1038
庸人自扰
庸人自扰 2021-02-04 20:41

I know javascript in the beginning level, but I have a problem.

I have 7 input elements in a form and I want all of them to be filled. I came up with t

4条回答
  •  礼貌的吻别
    2021-02-04 21:07

    With some simple vanilla JS, you can handle this in a lot more simplified way:

    JavaScript

    function validateForm(){
        var form = document.getElementById("register"), inputs = form.getElementsByTagName("input"), input = null, flag = true;
        for(var i = 0, len = inputs.length; i < len; i++) {
            input = inputs[i];
            if(!input.value) {
                flag = false;
                input.focus();
                alert("Please fill all the inputs");
                break;
            }
        }
        return(flag);
    }
    

    Then make sure you return the function within your form, either inline (bad practice):

    Or in a more unobtrusive way:

    window.onload = function(){
        var form = document.getElementById("register");
        form.onsubmit = function(){
            var inputs = form.getElementsByTagName("input"), input = null, flag = true;
            for(var i = 0, len = inputs.length; i < len; i++) {
                input = inputs[i];
                if(!input.value) {
                    flag = false;
                    input.focus();
                    alert("Please fill all the inputs");
                    break;
                }
            }
            return(flag);
        };
    };
    

提交回复
热议问题