用querystring中的值预填充窗体
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用querystring中的值预填充窗体相关的知识,希望对你有一定的参考价值。
Code matches querysting data to form feilds on the page based on the feild name.I've added the example querystring to the body of the page.
Found at: http://codingforums.com/showthread.php?t=198419
Code by: Old Pedant
<html> <head> 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>
以上是关于用querystring中的值预填充窗体的主要内容,如果未能解决你的问题,请参考以下文章