Home  >  Article  >  Web Front-end  >  分享一个验证表单是否为空的javascript通用方法

分享一个验证表单是否为空的javascript通用方法

WBOY
WBOYOriginal
2016-06-01 09:54:591029browse

实例代码如下:

<code class="language-html"> 
 
<script type="text/javascript"> 
function checkForm(form) { 
    for (var i = 0; i < form.elements.length; i++) { 
        if (form.elements[i].type == "text" && form.elements[i].value == "") { 
            document.write("Fill out ALL fields."); 
            return false; 
        } 
    } 
    return true; 
} 
</script> 
 
 
    <form onsubmit="return checkForm(this)"> 
        Please enter all requested information:<br> 
        First Name:<input type="text" name="firstName"><br> 
        Last Name:<input type="text" name="lastName"><br> 
        Rank:<input type="text" name="rank"><br> 
        Serial Number:<input type="text" name="serialNumber"><br> 
        <input type="submit"> 
    </form> 
 
</code>

本实例采用遍历的方法来获取表单元素,并判断元素是否为空。如果其中有一个为空,则return false,表单验证失败。

你可以把代码复制到这个页面运行一下。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn