Reputation: 875
I have the following URL: http://localhost:8888/datatest?username=JD042719
I want to pull in the "JD042719"
.
This problem does not require a 'Get' request.
Then the username value should be set to the value of another text box. Perhaps something like this:
HTML
<label for="Assoc">Associate ID</label>
<input type="text" name="AssocID" id="AssocID" required="required">
JavaScript
$(function associd(){
document.getElementById("AssocID").value=username;
});
Upvotes: 0
Views: 4840
Reputation: 2869
The answer below is quite outdated. Unless you need to support Internet Explorer, you should just use URLSearchParams as follows:
var username = (new URLSearchParams(window.location.search)).get("username");
Use the excellent function provided in this answer, like so:
Usage
var username = getParameterByName("username");
Function
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, " "));
}
The variable username
should now hold the value JD042719
(or whatever value is in the URL).
Upvotes: 5
Reputation: 159
location.search will provide you string after and with ?query="SEARCH" . Now do split and take out the term. These the simplest method·
Upvotes: 0
Reputation: 840
Unfortunately Javascript does not have fun built in ways to get to get these url variables. Some languages do such as PHP. So in javascript we have to be more creative. Here is a function that you can call to get a variable value if you know the name of the variable.
function GetUrlVar (varName) {
varName = RegExp ('[?&]' + name.replace (/([[\]])/, '\\$1') + '=([^&#]*)');
return (window.location.href.match (varName) || ['', ''])[1];
}
So now in your case you would call this function and pass in username like so
document.getElementById("AssocID").value=GetUrlVar('username');
EDIT: I looked back and I used this from a previous question so I wanted to give credit where it is due. Get a variable from url parameter using Javascript
Upvotes: 1
Reputation: 12900
Something quick and easy....
Use .split()
to break down the url and look for the username
parameter.
var theUrl = "http://localhost:8888/datatest?username=JD042719";
var args = theUrl.split("?");
for (var i = 0; i < args.length; i++) {
if (args[i].indexOf("username") > -1) {
alert(args[i]); //output: username=JD042719
}
}
Upvotes: 0
Reputation: 921
I would do something like this:
var url = window.location.href.split(/[=]/);
Then you could reference
url[1]
Upvotes: 1
Reputation: 2285
you must use $_GET
to do this "it's PHP not JS"
<?php $username=$_GET['username'];?>
<label for="Assoc">Associate ID</label>
<input type="text" name="AssocID" id="AssocID" required="required">
$(function associd(){
document.getElementById("AssocID").value=<?php echo $username; ?>
});
Upvotes: -1