简体   繁体   中英

Pressing enter on submit form

Why when i press enter it doesn't run the code , cause i put the code that should run in the if statement . When i press enter it console log it not run it properly.

document.getElementById('city-location').addEventListener('keyup', (e) => {
    const LOCATION = document.getElementById('city-location').value
    if(e.target.which == 13 || e.target.keyCode == 13) {
        weatherApi.changeLocation(LOCATION);
        storage.setStorage(LOCATION);
        getWeatherApi();
    } else {
        console.log('Wrong key pressed');
    }

    e.preventDefault();
})

Here is the markup:

<form id="weather-modal-form">
 <div class="form-group">
    <label for="city">City</label>
    <input type="text" id="city-location">
 </div>
</form>

You should add submit event for enter buttons.

 document.getElementById('weather-modal-form').addEventListener('submit', (e) => { e.preventDefault(); console.log("work's"); }) 
 <form id="weather-modal-form"> <div class="form-group"> <label for="city">City</label> <input type="text" id="city-location"> </div> </form> 

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