0

I'm trying to fill a text input using a URL parameter: http://127.0.0.1/index.html?uname="john"

<p class="control">
<input autofocus id="uname" class="input" 
  onchange="(sayhello(this.value))" 
  oninput="sayhello(this.value)" 
  placeholder="Enter your name" type="text">
</p>

I use the following script to pass the URL parameter into text input but the events don't work, they works only if I delete the input text and type it.

<script>
var uunme = window.location.href.match(/\?uname=(.*)/);
document.getElementById("uname").value = uunme[1];

</script>
3
  • sayhello is not a native function. Also, change/input events are not triggered when changing the value of an input programmatically. You've to manually call the event handler, or fire the change/input event. Commented Sep 7, 2017 at 17:34
  • 1
    Neither onchange nor oninput will trigger when you set the value programmatically. Commented Sep 7, 2017 at 17:35
  • stackoverflow.com/questions/6826707/… Commented Sep 7, 2017 at 17:43

1 Answer 1

0

Something like this?

var url_string = "https://example.com/?uname=foo"; // window.location.href
var url = new URL(url_string);
var uunme = url.searchParams.get("uname");
document.getElementById("uname").value = uunme;

function sayhello(text) {
  alert(text);
}
<p class="control">
  <input autofocus id="uname" class="input" onchange="sayhello(this.value);" oninput="sayhello(this.value);" placeholder="Enter your name" type="text">
</p>

I used the answer from the Stackoverflow question "How to get the value from the GET parameters?" to reliably retrieve the URL parameter uname. I also tidied up a few things.

Sign up to request clarification or add additional context in comments.

10 Comments

i know that, when the page loads the parametr foo is loaded in input text but the function doesnt work
The sayhello() function?
yes, only works if i delete the input text, and type it manual
In my example it's working. Can you maybe provide the code in your sayhello() function?
i use the same with your, when you run your code the function works ?? for me only work when i type something into input text
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.