简体   繁体   English

网址查询字符串中变量的javascript表单字段填充

[英]javascript form field population from variable in url query string

I would like to update a text field within a webform with a variable from the url query string using javascript. 我想使用javascript从url查询字符串中使用变量更新网络表单中的文本字段。

I do not have access to target the form id or name, only the field id and name 我无权定位表单ID或名称,只有字段ID和名称

Example url: www.xyz.com?name=Chris 网址范例:www.xyz.com?name = Chris

Example form code: 表单代码示例:

 <form method="post"> <input type="text" name="Name" id="Name"> <input type="submit" value="Submit"> </form> 

Appreciate the help Regards, Chris 感谢克里斯,克里斯

Use the following function to get the value from the URL. 使用以下函数从URL获取值。

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Then use the following code to update the input with the value. 然后,使用以下代码用该值更新输入。

document.getElementsByName('Name').value = getParameterByName('name');

update 更新

if you want to run the code when the page loads, just add the code to the bottom of the page in a script tag! 如果要在页面加载时运行代码,只需在脚本标签中将代码添加到页面底部即可! The script will run after the page loads and would change the value on the input using the query string. 该脚本将在页面加载后运行,并将使用查询字符串更改输入值。

You can get & extract the query string in JavaScript using the following Lines. 您可以使用以下行获取并提取JavaScript中的查询字符串。

var qrStr = window.location.search;
qrStr = qrStr.split("?")[1].split("=")[1];

to pass value.... 传递价值...

function PassValue()
 {
   var paramVal = "Hello ";
   window.open("Default.aspx?id=" + paramVal);
  }

   <asp:Button ID="Button1" runat="server" Text="Button"
   OnClientClick="PassValue();" onclick="Button1_Click" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM