JavaScript 使用查询字符串中的值预填充表单
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript 使用查询字符串中的值预填充表单相关的知识,希望对你有一定的参考价值。
<html>
<head>
<script type="text/javascript">
function populate(form)
{
if ( location.search == null || location.search.length < 1 ) return; // no querystring
var pairs = location.search.substring(1).split("&");
for ( var p = 0; p < pairs.length; ++p )
{
var pair = pairs[p].split("=");
var name = pair[0];
var value = unescape( pair[1].replace(/\+/g, " ") );
var fld = form.elements[name];
var ftype = null;
var farray = false;
var atype = Array;
if ( fld != null )
{
if ( fld.length != null && fld.length >= 1 && fld[0].type != null && fld[0].type != undefined )
{
ftype = fld[0].type;
farray = true;
} else {
ftype = fld.type;
}
}
switch ( ftype )
{
case "text": case "hidden": case "textarea":
if ( farray ) fld = fld[0]; // only handle first-named for this type
fld.value = value;
break;
case "select-one": case "select-multiple":
if ( farray ) fld = fld[0]; // only handle first-named for this type
for ( var o = 0; o < fld.options.length; ++o )
{
var opt = fld.options[o];
var oval = opt.value;
if ( oval == null || oval == "" ) oval = opt.text;
if ( oval == value )
{
opt.selected = true;
break;
}
}
break;
case "checkbox": case "radio":
if ( ! farray )
{
// single checbox or radio of that name:
fld.checked = true;
} else {
for ( var cr = 0; cr < fld.length; ++cr )
{
if ( fld[cr].value == value )
{
fld[cr].checked = true;
break;
}
}
}
break;
default:
alert("Unknown field type encountered for field " + name + ": " + ftype);
break;
} // end of switch
} // end of loop on fields from qs
}
</script>
</head>
<body onload="populate(document.TheForm);">
<p>
Example querystring to try:<br/> ?sel1=Three&sel2=2&sel2=4&cb1=2&cb1=3&rb1=C&text1=put+some+random+text+here&ta1=all+fun+and+games...
</p>
<form name="TheForm">
Text1<input type="text" name="text1" /><br/><br/>
Checkboxs: 1:<input type="checkbox" name="cb1" value="1" />
2: <input type="checkbox" name="cb1" value="2" />
3: <input type="checkbox" name="cb1" value="3" />
<br/><br/>
RB1<br/>
A<input type="radio" name="rb1" value="A" /><br/>
B<input type="radio" name="rb1" value="B" /><br/>
C<input type="radio" name="rb1" value="C" /><br/>
<br/><br/>
<textarea name="ta1" rows=4 cols=40></textarea>
<br/><br/>
Sel1:
<select name="sel1">
<option>One</option>
<option>Two</option>
<option>Three</option>
<option>Four</option>
</select>
<br/><br/>
Sel2:
<select name="sel2" multiple>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<br/>
</form>
</body>
</html>
以上是关于JavaScript 使用查询字符串中的值预填充表单的主要内容,如果未能解决你的问题,请参考以下文章