javascript获取所有的type为button按钮的input域

时间:2017-03-21
本文章向大家介绍js如何获取页面中所有的type为button按钮的input域,这里主要使用到document.mathForm.elements[x].type方法,需要的朋友可以参考一下本文的源代码。

问题:

我们向知道如何获取所有的type为button按钮的input域。

实现方法及源码:

document.mathForm获取所有表单的所有input域,然后使用document.mathForm.elements[x]获取每个input域,x表示索引,从0开始。再使用document.mathForm.elements[x].type获取每个域的type属性值,如果type属性值为button,则表示该input域为按钮button。

源码如下:

<html>
    <script language="JavaScript">
    var buttonCount = 0;
<!--from   http://www.manongjc.com   码农教程   -->
    for(var x=0; x<document.mathForm.length; x++)
    {
      if(document.mathForm.elements[x].type=="button")
        buttonCount++;      
    }
    document.write("Please select one of the ",buttonCount);  

    document.write(" buttons above to find out the answer to the math problem.");
    </script>    
    <form name="mathForm">
      <input type="button"
             name="4plus2"
             value="(4 + 2)"
             onClick="document.mathForm.answer.value='(4 + 2) = 6'">
      <input type="button"
             name="4minus2"
             value="(4 - 2)"
             onClick="document.mathForm.answer.value='(4 - 2) = 2'"><HR>
      Answer:
      <input type="text" name="answer">
    </form>
</html>

本文章向大家介绍了如何使用document.mathForm.elements[x].type来判断input域是否为button。