javascript實現的清空表單元素內容程式碼例項

admin發表於2017-03-24

本章節介紹一下如何利用javascript清空form表單所有表單元素的值,下面就通過程式碼例項介紹一下如何實現此功能。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
function clearForm(id){ 
  var formObj=document.getElementById(id); 
  if(formObj == undefined){ 
    return; 
  } 
  for(var i=0; i<formObj.elements.length; i++){ 
    if (formObj.elements[i].type == "text") {
      formObj.elements[i].value = ""; 
    } 
    else if(formObj.elements[i].type == "password"){ 
      formObj.elements[i].value = ""; 
    } 
    else if(formObj.elements[i].type == "radio"){ 
      formObj.elements[i].checked = false; 
    } 
    else if(formObj.elements[i].type == "checkbox"){ 
      formObj.elements[i].checked = false; 
    } 
    else if(formObj.elements[i].type == "select-one"){ 
      formObj.elements[i].options[0].selected = true; 
    } 
    else if(formObj.elements[i].type == "select-multiple"){ 
      for(var j = 0; j < formObj.elements[i].options.length; j++){ 
        formObj.elements[i].options[j].selected = false; 
      } 
    } 
    else if(formObj.elements[i].type == "file"){ 
      var file = formObj.elements[i]; 
      if(file.outerHTML){ 
        file.outerHTML = file.outerHTML; 
      }
      else{ 
        file.value = "";
      } 
    } 
    else if(formObj.element[i].type == "textarea"){ 
      formObj.elements[i].value = ""; 
    } 
  } 
} 
window.onload=function(){
  var obt=document.getElementById("bt");
  obt.onclick=function(){
    clearForm("myform")
  }
}
</script>
</head>
<body>
<form id="myform" action="#"> 
<ul> 
  <li>使用者名稱:<input type="text" name="username" value="螞蟻部落"/></li> 
  <li>密碼:<input type="text" name="pw" /></li> 
  <li><input type="button" id="bt" value="檢視效果" /></li> 
</ul> 
</form> 
</body>
</html>

相關文章