0

You can set the value of a input like this:

document.getElementById("location-search").value = "Somewhere";

but how do you actually trigger type event using Javascript and without using jQuery?

quarks
  • 33,478
  • 73
  • 290
  • 513
  • what you mean type event?. Can you little bit elaborate this – Sivabalan May 07 '18 at 14:49
  • 1
    Possible duplicate of [Trigger a keypress/keydown/keyup event in JS/jQuery?](https://stackoverflow.com/questions/3368578/trigger-a-keypress-keydown-keyup-event-in-js-jquery) the vanilla JS answer is right there if you scroll down to here: https://stackoverflow.com/a/37542647/2008111 – caramba May 07 '18 at 14:49
  • https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events – Daniel Beck May 07 '18 at 14:50
  • 1
    @Sivabalan he means typing on the keyboard "type" – caramba May 07 '18 at 14:50
  • assuming you have Id 'form' you can call document.getElementById("form").submit(); – reddiky May 07 '18 at 14:51
  • you mean trigger some event when some value added proramatically ? – Muhammad Usman May 07 '18 at 14:53
  • @caramba Sorry i mistake. i think you have edited your comment Or i eyes are bad. I removed the comment – Sivabalan May 07 '18 at 14:54
  • This might help: https://stackoverflow.com/questions/35659430/how-do-i-programmatically-trigger-an-input-event-without-jquery – Mamun May 07 '18 at 15:09
  • One more option https://stackoverflow.com/questions/961532/firing-a-keyboard-event-in-javascript – Asons May 07 '18 at 15:54

2 Answers2

0

You can use custom events. Fire an event when ever you add value to input. And add a listener against this event.

var type = new CustomEvent("typing", {});
function typed() {
    document.getElementById("d").value = "Somewhere";
    document.dispatchEvent(type);
}


document.addEventListener("typing", function(e) {
    console.log("Something typed");
});

typed();
<input type="text" id="d" />

Here

Muhammad Usman
  • 10,039
  • 22
  • 39
  • I mean, I really need to trigger real keyboard type event because I am using PhantomJS and that typing needs to be triggered so certain function will be triggered in the website. – quarks May 07 '18 at 15:28
0

Using the approach mentioned : Here

The change would the event type instead of HTMLEvents we use KeyboardEvent.

document.getElementById("d").addEventListener('keydown',function(e){
    document.getElementById("log").innerHTML += '</br> keydown Triggered'
});


document.getElementById("triggeringStuff").addEventListener('click',function(){
    var str = "Something";
    var elem = document.getElementById("d");
    str.split('').map(function(item){
        var e = document.createEvent('KeyboardEvent');
        e.initEvent('keydown');
        elem.value += item;
        elem.dispatchEvent(e);
    });
    
});
<input type="text" id="d" />

<button id="triggeringStuff">Trigger Stuff</button>


<p id="log">Logs :</p>
Rainbow
  • 6,772
  • 3
  • 11
  • 28