How do I use javascript to prevent form submission because of empty fields?

后端 未结 4 1417
慢半拍i
慢半拍i 2021-01-24 01:44

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is \"form\" and the input name is \"name\".

4条回答
  •  醉话见心
    2021-01-24 02:26

    This is untested code but it demonstrates my method.

    It will check any text field in 'form' for empty values, and cancel the submit action if there are any.

    Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.

    window.onload = function (event) {
        var form = document.getElementsByName('form')[0];
        form.addEventListener('submit', function (event) {
            var inputs = form.getElementsByTagName('input'), input, i;
            for (i = 0; i < inputs.length; i += 1) {
                input = inputs[i];
                if (input.type === 'text' && input.value.trim() === '') {
                    event.preventDefault();
                    alert('You have empty fields remaining.');
                    return false;
                }
            }
        }, false);
    };
    

提交回复
热议问题