当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


HTML Form length用法及代码示例


DOM表单长度属性用于返回表单中包含的输入字段的数量。

用法:

formObject.length

返回值:它返回一个数字值,该值代表表单中输入字段或元素的数量。


示例1:返回输入字段数。

<!DOCTYPE html> 
<html> 
  
<body style="text-align:center;"> 
    <h1 style="color:green;"> 
      GeeksForGeeks 
  </h1> 
    
    <h2>DOM Form length Property. 
  </h2> 
    
    <form id="users" 
          action="#"> 
        First name:
        
        <input type="text" 
               name="fname"
               value="Manas"> 
        <br> Last name:
        
        <input type="text"
               name="lname" 
               value="Chhabra"> 
        <br> 
        
        <input type="submit" 
               value="Submit"> 
    </form> 
  
    <p>Click the "Try it" button to return  
      the number of elements contained in the form.</p> 
  
    <button onclick="myGeeks()"> 
      Try it 
  </button> 
  
    <p id="sudo" 
       style="font-size:25px;color:green;"> 
  </p> 
  
    <script> 
        function myGeeks() { 
            
            // Return the number of input field 
            var x = 
                document.getElementById( 
                  "users").length; 
            
            document.getElementById("sudo").innerHTML =  
              "There are " + x +  
              " Input Field contained by the form."; 
        } 
    </script> 
  
</body> 
  
</html>

输出:

在单击按钮之前:

单击按钮后:

示例2:返回输入字段的值。

<!DOCTYPE html> 
<html> 
  
<body style="text-align:center;"> 
    <h1 style="color:green;"> 
      GeeksForGeeks 
  </h1> 
    
    <h2>DOM Form length Property.</h2> 
    <form id="users" 
          action="#"> 
        First name:
        
        <input type="text" 
               name="fname" 
               value="Manas"> 
        <br> Last name:
        
        <input type="text"
               name="lname" 
               value="Chhabra"> 
        <br> 
        
        <input type="submit"
               value="Submit"> 
    </form> 
  
    <p>Click the "Try it" button to return 
      the value of each input field or element  
      contained in the form.</p> 
  
    <button onclick="myGeeks()">Try it</button> 
  
    <p id="sudo" style="font-size:25px;color:green;"> 
  </p> 
  
    <script> 
        function myGeeks() { 
            
            //  Return values of input field. 
            var x = document.getElementById("users"); 
            var text = ""; 
            var i = 0; 
            for (i = 0; i < x.length; i++) { 
                text = text + x.elements[i].value + "<br>"; 
            } 
            document.getElementById("sudo").innerHTML = text; 
        } 
    </script> 
  
</body> 
  
</html>

输出:

在单击“打开”按钮之前:

单击按钮后:

支持的浏览器:下面列出了DOM Form length属性支持的浏览器:

  • 谷歌浏览器
  • IE浏览器
  • Firefox
  • Opera
  • Safari


相关用法


注:本文由纯净天空筛选整理自ManasChhabra2大神的英文原创作品 HTML | DOM Form length Property。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。