0

I'm creating an onload page that contain search input, and the value is generated from url

http://localhost/example?i%search%this

in the onload page i create this =

<body onload="myFunction()">
// this is where i put the input search that needs Enter to active search
<input type="text" class="form-control searchable-input floatL value-not-empty" placeholder="Search Badan Usaha" name="s545858fe" id="s545858fe">
</body>

<script>
function myFunction() {
    var newURL = window.location.search.substr(1);
    var uri_dec = decodeURIComponent(newURL);
    document.getElementById("s545858fe").value = uri_dec;
}
</script>

my actual results is that i get "i search this" text in my input search, but its not execute the search because the search need enter key to execute

1 Answers1

0

You can trigger an Enter keypress inside the <input> by creating a KeyboardEvent() and then dispatching the event:

const entry = document.getElementById('s545858fe');

entry.addEventListener('keypress', function (event) {
    console.log('Keypress in entry with value: ' + this.value);
}, false);

function myFunction() {
    const evt = new KeyboardEvent('keypress', {});

    entry.focus();
    entry.value = "new value";
    entry.dispatchEvent(evt);
}
<body onload="myFunction()">
<input type="text" class="form-control searchable-input floatL value-not-empty" placeholder="Search Badan Usaha" name="s545858fe" id="s545858fe">
</body>
skyline3000
  • 7,639
  • 2
  • 24
  • 33
  • this dispatchEvent actually works but only if i delete the function myFunction() {} but when i delete it, its not reworking when i reload the page. the value is still the old value. can you give me pointer – www.cahyonegoro.com Aug 05 '19 at 03:25
  • Can you please elaborate what you mean it only works if you delete the function? Can you update your code? – skyline3000 Aug 05 '19 at 18:50