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>
mustaccio
  • 18,234
  • 16
  • 48
  • 57
roxy678
  • 1
  • 1
  • 1
  • `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. – Teemu Sep 07 '17 at 17:34
  • 1
    Neither `onchange` nor `oninput` will trigger when you set the value programmatically. – stephen.vakil Sep 07 '17 at 17:35
  • https://stackoverflow.com/questions/6826707/javascript-onchange-event-does-not-work-with-value-change-in-text-input-o – epascarello Sep 07 '17 at 17:43

1 Answers1

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.

Ari Seyhun
  • 11,506
  • 16
  • 62
  • 109