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

150
Visualizações
¿Cómo simular el botón Entrar para replicar el botón Enviar?

Estoy creando una aplicación meteorológica con un área de texto, si hace clic en "enviar", verá los resultados meteorológicos. Ahora, quiero hacerlo para que pueda hacer clic en entrar para ver los datos. este es un código:

 <section class="inputs"> <input type="text" placeholder="Enter any city..." id="cityinput"> <input type="submit" value="Submit" id="add"> <button placeholder="submit" id="add"></button> </section>

Este es un código javascript:

 btn.addEventListener('click', function(){ //This is the api link from where all the information will be collected fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputval.value+'&appid='+apik) .then(res => res.json()) //.then(data => console.log(data)) .then(data => { //Now you need to collect the necessary information with the API link. Now I will collect that information and store it in different constants. var nameval = data['name'] var tempature = data['hourly']['pop'] //Now with the help of innerHTML you have to make arrangements to display all the information in the webpage. city.innerHTML=`Weather of <span>${nameval}<span>` temp.innerHTML = ` <span>${ tempature} </span>` })
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Debe adjuntar un oyente a su área de texto, si el usuario presiona enter , entonces ejecuta su llamada (aquí simulada por una alerta) y evita el valor predeterminado para no entrar en una nueva línea. En cualquier otro caso, simplemente no tome ninguna acción.

 const textArea = document.querySelector('textarea'); textArea.addEventListener('keydown', e => { if (e.key === 'Enter') { window.alert('Sending data...'); e.preventDefault(); } });
 <textarea placeholder="Type and press enter"></textarea>

Simplemente puede poner el código de submit en una función y llamar a la función en ambos casos:

 function submitAction() { fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputval.value+'&appid='+apik) .then(res => res.json()) .then(data => { const nameval = data['name'] const tempature = data['hourly']['pop'] city.innerHTML=`Weather of <span>${nameval}<span>` temp.innerHTML = ` <span>${ tempature} </span>` }); }

Después:

 if (e.key === 'Enter') { submitAction(); e.preventDefault(); }

Y:

 btn.addEventListener('click', () => submitAction());
about 4 years ago · Santiago Trujillo Relatório

0

Puede usar un formulario HTML y usar el evento de envío de formulario:

 <form id="form"> <input type="text" placeholder="Enter any city..." id="cityinput" /> <button type="submit">Submit</button> </form>

Dentro del detector de eventos, puede leer el valor de la entrada una vez que se activa el evento de submit . Alternativamente, puede buscar el valor de entrada dentro del objeto de event .

 var form = document.getElementById('form'); form.addEventListener('submit', function(event) { const inputValue = document.querySelector('input').value; event.preventDefault(); fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputValue+'&appid='+apik) .then(res => res.json()) .then(data => { var nameval = data['name'] var tempature = data['hourly']['pop'] city.innerHTML=`Weather of <span>${nameval}<span>` temp.innerHTML = ` <span>${ tempature} </span>` }) });
about 4 years ago · Santiago Trujillo Relatório

0

Debe crear un oyente para el evento keydown y verificar si la tecla en la que se hizo clic es enter:

 const textarea = document.querySelector(".some-class"); textarea.addEventListener("keydown", function(e) { if(e.key === "Enter") { // your code } });
 <textarea class="some-class"></textarea>
about 4 years ago · Santiago Trujillo 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