1

I would like to update a text field within a webform with a variable from the url query string using javascript.

I do not have access to target the form id or name, only the field id and name

Example url: 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

chris
  • 861
  • 1
  • 7
  • 15

2 Answers2

2

Use the following function to get the value from the 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.

Imesh Chandrasiri
  • 5,558
  • 15
  • 60
  • 103
  • Thanks for the response. Where do i actually call the get Element line of javascript to parse the variable? Would it be using a body on load event or within the form field itself. Much thanks – chris Aug 20 '15 at 04:35
  • where do you want to get the value and update the input field? – Imesh Chandrasiri Aug 20 '15 at 04:53
  • the value im getting is in the url and i want to add it to the input field so its visible once when the page loads? How would i do this please? – chris Aug 20 '15 at 05:08
  • Im sorry i just tried to do what you said, and i couldnt get it to work in this example: http://content.engagedigital.com.au/Zap/test.html?Name=Test – chris Aug 20 '15 at 05:57
0

You can get & extract the query string in JavaScript using the following Lines.

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" />
Anoop B.K
  • 1,484
  • 2
  • 17
  • 31
  • How to i use javascript to add the value from the url into the form field please? Is it via a body onload event, or would i put the JS call directly in the field value tag - i have no idea :s – chris Aug 20 '15 at 05:32
  • u mean to pass a value ?, check i have edited the code above – Anoop B.K Aug 20 '15 at 05:40