Ajax through JS code to automatically obtain the form element value of the sample code

Time:2021-4-16

When we use ajax, we usually need to get the form element value, and then send it to the server-side program in the background for processing. If there are not many form elements, we often get the form element value by get. But if there are many form elements, we need to get the form element value by post. How to get the form element value? The following is a JS code to automatically get the value of the form element.

Function getformquerystring (frmid) // frmid is the ID number of the form. Please name an ID number in the form first
{
var frmID=document.getElementById(frmID);
var i,queryString = "", and = "";
var item;
var itemValue;
for( i=0;i<frmID.length;i++ )
{
item = frmID[i];
if ( item.name!='' )
{
if ( item.type == 'select-one' )
{
itemValue = item.options[item.selectedIndex].value;
}
else if ( item.type=='checkbox' || item.type=='radio')
{
if ( item.checked == false )
{
continue; 
}
itemValue = item.value;
}
else if ( item.type == 'button' || item.type == 'submit' || item.type == 'reset' || item.type == 'image')
{
continue;
}
else
{
itemValue = item.value;
}
itemValue = escape(itemValue);
queryString += and + item.name + '=' + itemValue;
and="&";
}
}
return queryString;
}

Call method: call the above JS function directly in Ajax to get the value of all elements in the form.