在提交表单上按Enter

时间:2019-06-20 06:41:56

标签: javascript forms events submit

为什么当我按Enter键时它不会运行code,导致我将应运行的代码放在if statement中。 当我按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();
})

这是标记:

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

1 个答案:

答案 0 :(得分:3)

您应该为输入按钮添加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>