Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
async function to trigger both with the search button and by pressing the "enter" key on the keyboard in the input field

I have an async function which works only when I click on the search button, but I want the function to start also if I press the "enter" key on the keyboard.

Is this possible with Vanilla Javascript and async function?

I made several attempts, but it seems not to be working.

html

<input type="text" id="input-search" placeholder=""><span><button id="search-button">Search</button></span>

Js

let userName = document.querySelector("#username");
let button = document.querySelector("#search-button");

button.onclick = async function getData() {
  let username = document.getElementById("input-search").value;

  axios
    .get(`https://api.templatewebsite`)

    .then(async (response) => {
      let data = await response.data;
      if (response.status !== 200) {
        throw new Error(response.status);
      } else {
        console.log(data);
      }
    });
};

I tried to keep the code snippets short, to avoid unnecessary information.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Yes, you can do it like this:

  let userName = document.querySelector('#username');
  let button = document.querySelector('#search-button');
  let input = document.querySelector('#input-search')
  async function getData() {
    // do some async actions
    alert('getData called')
  }
  button.onclick = getData; 
  input.addEventListener('keyup', function(e){
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code == 13) { 
      getData();
    }
  })  
<input type="text" id="input-search" placeholder=""><span><button id="search-button">Search</button></span>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You have two options, first is to wrap it in <form> component and handle this code on submit. Second is to add event listener on input and check if its enter:

userName.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
   
    // Magic happens here
 
   }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

I tried to put the code suggested by @Shamloo and tried to adapt it to my code. It throws an error when it tries to grab the value of the input field, after the axios API call.

Probably I put the code in the wrong place, because it throws an error even if the input field contains the right value.

I did like this:

let input = document.querySelector('#input-search')

async function getData(){

    document.querySelector('#input-search').value
    
    //API CALL  with axios     

        axios.get(`https://api.webtemplate{input}`)
                    
        .then(
            
        async response => {
            
        let data = await response.data

    //if the request can't be processed (data is not found)

        if (response.status !== 200) {
        
            throw new Error(response.status);
        
            } else {

                  //request works, data is found
console.log(data)

outside of the function, at the bottom of the code

   button.onclick = getData; 
        input.addEventListener('keyup', function(e){
          var code = (e.keyCode ? e.keyCode : e.which);
          if(code == 13) { 
            getData();
          }
        }) 
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda