简体   繁体   English

在提交表单上按Enter

[英]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 . 为什么当我按Enter键时它不运行code ,导致我将应运行的代码放在if statement When i press enter it console log it not run it properly. 当我按enter键时, console log无法正常运行。

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. 您应该为输入按钮添加submit事件。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM