JavaScript獲取form下所有input元素

antzone發表於2017-03-15

有時需要獲取form表單裡面所有input元素,然後進行統一操作。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
window.onload=function(){
  var theform=document.getElementById("theform");
  var inputs=theform.getElementsByTagName("input");
  for(var i=0;i<inputs.length;i++){
    alert(inputs[i].name);
  }
}
</script>
</head>
<body>
<form name="theform" id="theform">
<input type="text" name="username" />
<input type="text" name="address" />
<input type="password" name="pw" />
<input type="button" name="bt" value="螞蟻部落" />
</form>
</body>
</html>

以上程式碼實現可以獲取表單中所有的input元素。但實際應用中可能要獲取哪一型別的標籤,比如文字型別或者密碼型別,下面對程式碼進行一下修改:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
window.onload=function(){
  var theform=document.getElementById("theform");
  var inputs=theform.getElementsByTagName("input");
  for(var i=0;i<inputs.length;i++){
    if(inputs[i].getAttribute("type")=="text")
      alert(inputs[i].name);
    }
  }
}
</script>
</head>
<body>
<form name="theform" id="theform">
<input type="text" name="username" />
<input type="text" name="address" />
<input type="password" name="pw" />
<input type="button" name="bt" value="螞蟻部落" />
</form>
</body>
</html>

以上程式碼實現了對於標籤的篩選功能。

相關文章