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

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

WBOY
Release: 2016-06-01 09:54:59
Original
1054 people have browsed it

实例代码如下:

<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>
Copy after login

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template