0

I am new to JavaScript coding with html and the things that's bugging me right now is passing a variable to another page in java script. So my codes for the first page are:

<html>
<head><title>lol1</title></head>
<body>
<form action="lol2.html">
<input  type="text" name ="firstname" placeholder="First Name">
<input  type="text" name="lastname" placeholder="Last Name">
<input  type="Submit" value="Submit" >
</form>
</body>
</html>

and second page are:

<html>
<head>
<title>
lol2
</title>
</head>
<body>
<script>
    var queryString = decodeURIComponent(window.location.search);
    var queries = queryString.split();
    document.write(queries); 
</script> 
</body>
</html>

After I enter the value in the text box it takes me to the second page but the result is shown like this:

enter image description here

so how do i get rid of the "firstname=" and "Secondname="? or find an effective way to solve problem.

Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
Dev Patel
  • 35
  • 1
  • 8
  • This seems kind of related to this question [https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Will Frautschy Jun 15 '18 at 15:32
  • Possible duplicate of [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Albert Einstein Jun 15 '18 at 15:36
  • @KiranShahior@WillFrautschy as i mentioned above i am new to coding and i don't really understand queries. – Dev Patel Jun 15 '18 at 15:41

3 Answers3

3

JavaScript has a built in method for this: URL() and searchParams

You can use it like:

let params = (new URL(document.location)).searchParams;
let firstname = params.get("firstname");
let lastname = params.get("lastname");
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38
1

Your problem really doesn't have anything to do with textboxes or forms or passing data from one page to another. It's simply a matter of how you are attempting to extract the querystring.

You must pass a string to the .split() method for it to actually perform the split:

var queryString = "firstName=Scott&lastName=Marcus";
var queries = queryString.split("&");  // <-- You weren't passing a string to split on
// Get each name/value pair:
console.log(queries[0]); 
console.log(queries[1]); 

// Get just the values:
console.log(queries[0].split("=")[1]); 
console.log(queries[1].split("=")[1]); 
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

You can use URLSearchParams, specifically the URLSearchParams.values() method to get just the values. Just keep in mind browser compatibility if you are going to use this on the web.

DC.Azndj
  • 1,346
  • 12
  • 13