Javascript eventListener not working every time I click

I have the following code that should execute every time I press F9 or F10, but it only does it every time I hit it?

I have an onchange event associated with a select box that does not fire every time I press F9 or F10, just at another time or so. I can say that ALERTS only shoot every time I press the key.

What gives?

document.addEventListener('keydown', function(e){
        if( e.keyCode == '120' ){
            alert("yo");
            var curPosition = document.getElementById('unpostedOrders').options.selectedIndex;
            document.getElementById('unpostedOrders').selectedIndex =(curPosition-1);
            var invoice = document.getElementById('unpostedOrders').value;
            getOrderToModify(invoice);
        }
        if( e.keyCode == '121' ){
            alert("gibear");
            var curPosition = document.getElementById('unpostedOrders').options.selectedIndex;
            document.getElementById('unpostedOrders').selectedIndex =(curPosition+1);
            var invoice = document.getElementById('unpostedOrders').value;
            getOrderToModify(invoice);
        }
    }, false);      

Found an answer to add:

document.addEventListener('keydown', function(e){
        e.stopPropagation(); // **put this line in your code**
        e.preventDefault(); // **put this line in your code**
        if( e.keyCode == '120' ){
        ...

Thanks Rakesh Chohan!

+4
source share
2 answers

try it

 document.addEventListener('keydown', function(e){
     e.stopPropagation(); // **put this line in your code**
    if( e.keyCode == '120' ){
        alert("yo");
        var curPosition = document.getElementById('unpostedOrders').options.selectedIndex;
        document.getElementById('unpostedOrders').selectedIndex =(curPosition-1);
        var invoice = document.getElementById('unpostedOrders').value;
        getOrderToModify(invoice);
    }
    if( e.keyCode == '121' ){
        alert("gibear");
        var curPosition = document.getElementById('unpostedOrders').options.selectedIndex;
        document.getElementById('unpostedOrders').selectedIndex =(curPosition+1);
        var invoice = document.getElementById('unpostedOrders').value;
        getOrderToModify(invoice);
    }
}, false);     

"gibear" , F10 Key , , F10, , (.. firefox ), F10, . , , .

, F10, F10

0

, selectedIndex:

document.getElementById('unpostedOrders').selectedIndex =(curPosition-1);

:

document.getElementById('unpostedOrders').options.selectedIndex = (curPosition-1);

options, selectedIndex.

, ,

0

Source: https://habr.com/ru/post/1535484/


All Articles