Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda