简体   繁体   中英

addEventListener 'submit' working properly when clicking on button but not when pressing enter

it's my first time using the submit event on a form. Rather than submitting, I have used preventDefault() and then added some code to execute a search. When I press the search button, it works properly, creating a div where it loads the search results. When I press enter, it works properly up to the point where it has to append the new div to the html.

This is the function that creates the div

const crearDivResultados = function() {
    const divResultados = document.createElement('div');
    divResultados.setAttribute("id", "resultados");
    contenedorResultados.append(divResultados);
}

This is the rest of the code.

const formulario = document.forms.buscador
formulario.addEventListener('submit', (event) => {
    event.preventDefault();
    let inputValor = inputBusqueda.value;
    contenedorResultados.innerHTML = '';
    crearTitulo(inputValor, contenedorResultados);
    crearDivResultados();
    let resultados = document.querySelector('#resultados');
    console.log(resultados);
    buscarGifs(inputValor).then (resp => {
        mostrarResultados(resp.data);
    })

    botonBusquedaDesplegado.style.display = 'none';
    contenedorResultados.style.display = 'block';
    resultados.style.display = 'flex';
})

The error (Uncaught (in promise) ReferenceError: resultados is not defined) appears in this line of code:

let resultados = document.querySelector('#resultados');

ONLY when submitting with enter key. When clicking the button it works just fine.

Thank you!!!

Event type Submit means the submit button is clicked. If you want to listen to another event type, use keypress

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM