tengo este formulario:
<form> <label for="locationsearch">Location:</label> <input type="search" id="locationsearch" name="locationsearch" /> </form>Quiero agregar un eventListener cuando presiono enter en la entrada (es decir, #ubicaciónbúsqueda). Intenté hacer esto:
const locationSearch = document.getElementById("locationsearch"); locationSearch.addEventListener("search", () => { console.log("search entered"); });y esto:
const locationSearch = document.getElementById("locationsearch"); locationSearch.onsubmit = function () { console.log("search entered"); };Ambos no están registrados en la consola.
¿Cuál es la forma correcta/mejor de realizar esta acción?
El evento onsubmit sucedería en el formulario en sí, no en la entrada. Por lo tanto, podría usar una identificación en el formulario para apuntarlo directamente.
const locationSearch = document.getElementById("locationsearch"); locationSearch.onsubmit = function () { console.log("search entered"); }; <form id="locationsearch"> <label for="locationsearch">Location:</label> <input type="search" name="locationsearch" /> </form>Podría manejarlo controlador de eventos keydown del elemento de entrada. Y verifique el código de la tecla si se presiona la tecla Enter.
const locationSearch = document.getElementById("locationsearch"); locationSearch.addEventListener("keydown", (e) => { if (e.code === 'Enter') { // Do Something ? Search } });Puede usar el evento de pulsación de tecla para esto.
const locationSearch = document.getElementById("locationsearch"); locationSearch.addEventListener("keypress", () => { if (event.key === "Enter") { event.preventDefault(); let inputVal = document.getElementById("locationsearch").value; console.log("search entered "+inputVal); document.getElementById("locationsearch").value = ""; } }); <form> <label for="locationsearch">Location:</label> <input type="search" id="locationsearch" name="locationsearch" /> </form>