Simulate click without calling function directly

1

Using pure javascript, I wanted to click a button and trigger the events of it, but the important thing is that I do not want to call the function directly. So far I have tried this:

var send = document.getElementsByName("send");
window.addEventListener("keyup", function( e ){
    if(e.which == 13 || e.keyCode == 13){
        send.dispatchEvent(new Event('click'));
    }
});

I have searched in several articles, but I need the equivalent of jQuery element.click(); , but the articles only teach to call the function directly interconnected to the element.

<button name="send" onclick="alert('foo')">Enviar</button>

Using pure javascript, as I clicked this button without being directly or calling the function that is in onclick

    
asked by anonymous 22.04.2015 / 22:51

2 answers

2

Your code seems to me to be correct, it only has one thing wrong getElementsByName returns a list of items (equivalent to array ), the right thing would be:

var send = document.getElementsByName("send");
window.addEventListener("keyup", function( e ){
    if(e.which == 13 || e.keyCode == 13){
        send[0].dispatchEvent(new Event('click'));//send[0] pega o primeiro button que achar
    }
});
    
22.04.2015 / 23:11
0

You have aply

Response in English

var elem = document.getElementById("linkid");
if (typeof elem.onclick == "function") {
    elem.onclick.apply(elem);
}
    
22.04.2015 / 23:14