0

I get URL parameters using Javascript but i can't use those variables in my html. the JS code is this:

<script>
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("name");
console.log(c);
</script>

and my URL is localhost:8000/something?name=ABC.here i can get the value of name and show it in the browser console but when i try to set the value of an input tag in my HTML it doesn't do it and raises some errors. my JS and html is like:

<script>
    var url_string = window.location.href; //window.location.href
    var url = new URL(url_string);
    var c = url.searchParams.get("name");
    document.getElementById("user").value =url.searchParams.get("name");
    </script>
<input id="user" value"">

this should have changed the value of the input tag but doesn't.

Parsa
  • 63
  • 1
  • 3
  • 14
  • 2
    *'it doesn't do it and raises some errors'* - Please provide the error messages. – Joe Clay Mar 29 '18 at 15:21
  • html is a markup language and has no access to url params, research php and `$_GET` - probs can do something with JS but is not my area of expertise – treyBake Mar 29 '18 at 15:21

2 Answers2

5

if your #user input is call before the DOM content is loaded,

document.getElementById("user").value

javascript can't find it so he try to set "value" of an undefined element

try this :

<input id="user" value="">    
<script>
    var url_string = window.location.href; //window.location.href
    var url = new URL(url_string);
    var c = url.searchParams.get("name");
    document.getElementById("user").value = c;
</script>
Julien Amblard
  • 121
  • 1
  • 3
0

If you only have one URL parameter this will work. Just make sure that your input element is defined first.

A working copy JsFiddle static input

HTML

<input id="user" value="">

JS

var url = "localhost:8000/something?name=ABC" //replace with code to get url
var name = url.substring(url.indexOf("=") + 1);  
document.getElementById("user").value = name;

If you need the input element to be defined after you get the URL parameter:

A working copy JsFiddle dynamic input

HTML

<div id="myDiv"> </div>

JS

var url = "localhost:8000/something?name=ABC" //replace with code to get url
var name = url.substring(url.indexOf("=") + 1);  

var parent = document.getElementById("myDiv");
var input = document.createElement("input");
input.value = name;
parent.appendChild(input)
bazinga
  • 38
  • 4