js simple way to get all data of form form

<script type="text/javascript"> 
  
//获取指定form中的所有的<input>对象  
function getElements(formId) {  
  var form = document.getElementById(formId);  
  var elements = new Array();  
  var tagElements = form.getElementsByTagName('input');  
  for (var j = 0; j < tagElements.length; j++){ 
     elements.push(tagElements[j]); 
  
  } 
  return elements;  
}  
  
//获取单个input中的【name,value】数组 
function inputSelector(element) {  
 if (element.checked)  
   return [element.name, element.value];  
}  
    
function input(element) {  
  switch (element.type.toLowerCase()) {  
   case 'submit':  
   case 'hidden':  
   case 'password':  
   case 'text':  
    return [element.name, element.value];  
   case 'checkbox':  
   case 'radio':  
    return inputSelector(element);  
  }  
  return false;  
}  
  
//组合URL 
function serializeElement(element) {  
  var method = element.tagName.toLowerCase();  
  var parameter = input(element);  
   
  if (parameter) {  
   var key = encodeURIComponent(parameter[0]);  
   if (key.length == 0) return;  
   
   if (parameter[1].constructor != Array)  
    parameter[1] = [parameter[1]];  
      
   var values = parameter[1];  
   var results = [];  
   for (var i=0; i<values.length; i++) {  
    results.push(key + '=' + encodeURIComponent(values[i]));  
   }  
   return results.join('&');  
  }  
 }  
  
//调用方法   
function serializeForm(formId) {  
  var elements = getElements(formId);  
  var queryComponents = new Array();  
   
  for (var i = 0; i < elements.length; i++) {  
   var queryComponent = serializeElement(elements[i]);  
   if (queryComponent)  
    queryComponents.push(queryComponent);  
  }  
   
  return queryComponents.join('&'); 
}  
  
</script>

How to use

<body>       
<form id="login" name="login" method="post" action="result.jsp"> 
<input name="user" type="text"/> 
<input name="sex" type="radio" value="man"/> 
<input name="sex" type="radio" value="woman"/> 
interest:<input type="checkbox" name="interest" value="piu">PIU <input type="checkbox" name="interest" value="dss">DSS <input type="checkbox" name="interest" value="ddr">DDR<br>  
<input type="hidden" name="from" value="welcome"><br>  
<input type="button" name="submit" value="submit" onclick="getFormInfo();">  
</form> 
</body>


function getFormInfo(){ 
  var params = serializeForm('login'); 
  alert(params); 
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325147237&siteId=291194637