'is there an alternative to onfocusout() function?

I have the function onfocusout() that runs another function selectEntite(), inside an input like the following code :

<input onfocusout="selectEntite();" type="text" placeholder="Entité" id="entityName" class="inputSelect" name="entityName" style="width: 60%" />

when the user leave the input, the function run. i want to change it until the user tap the keyboard enter.



Solution 1:[1]

Try this:

<input onkeydown="selectEntite(this);" type="text" placeholder="Entité" id="entityName" class="inputSelect" name="entityName" style="width: 60%" />
function selectEntite(ele) {
    if(event.key === 'Enter') {
        alert(ele.value);        
    }
}

Solution 2:[2]

you can add an addEventListener() to the input field that listens for key presses. Then check if enter is pressed, then you can execute some code. –

let el = document.getElementById("entityName")
el.addEventListener("keydown",(event) => {
    if (event.key === "Enter") {
        // Enter key was hit
    }
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vimal
Solution 2 Kokodoko