由于空字段,如何使用javascript来阻止表单提交?

问题描述:

如何在javascript中创建脚本以输出错误并阻止表单中的空字段提交表单?假设表单名称为form,输入名称为name。我在使用PHP时遇到麻烦并不总是正确处理空字段,所以我希望将其作为备份。感谢任何帮助。

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". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.

HTML代码: -

HTML Code :-

<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>

Javascript代码: -

Javascript Code :-

  function runMyFunction()
    {
        if (document.getElementsByName("name")[0].value == "")
        {
            alert("Please enter value");
        }
        else
        {
            var form= document.getElementsByName("form")[0];
            form.submit();        
        }
    }