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>` })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());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>` }) });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>