Enter key press event in JavaScript

2018-12-31 08:41发布

I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call a javascript function (User defined), but when I press it, the form is submitted.

How do I prevent the form from being submitted when the enter key is pressed?

14条回答
千与千寻千般痛.
2楼-- · 2018-12-31 09:25

A react js solution

 handleChange: function(e) {
    if (e.key == 'Enter') {
      console.log('test');
    }


 <div>
    <Input type="text"
       ref = "input"
       placeholder="hiya"
       onKeyPress={this.handleChange}
    />
 </div>
查看更多
无色无味的生活
3楼-- · 2018-12-31 09:26

event.key === "Enter"

More recent and much cleaner: use event.key. No more arbitrary number codes!

const node = document.getElementsByClassName(".mySelect")[0];
node.addEventListener("keydown", function(event) {
    if (event.key === "Enter") {
        event.preventDefault();
        // Do more work
    }
});

Mozilla Docs

Supported Browsers

查看更多
皆成旧梦
4楼-- · 2018-12-31 09:28

A much simpler and effective way from my perspective should be :

function onPress_ENTER()
{
        var keyPressed = event.keyCode || event.which;

        //if ENTER is pressed
        if(keyPressed==13)
        {
            alert('enter pressed');
            keyPressed=null;
        }
        else
        {
            return false;
        }
}
查看更多
孤独总比滥情好
5楼-- · 2018-12-31 09:28

native js (fetch api)

document.onload = (() => {
    alert('ok');
    let keyListener = document.querySelector('#searchUser');
    // 
    keyListener.addEventListener('keypress', (e) => {
        if(e.keyCode === 13){
            let username = e.target.value;
            console.log(`username = ${username}`);
            fetch(`https://api.github.com/users/${username}`,{
                data: {
                    client_id: 'xxx',
                    client_secret: 'xxx'
                }
            })
            .then((user)=>{
                console.log(`user = ${user}`);
            });
            fetch(`https://api.github.com/users/${username}/repos`,{
                data: {
                    client_id: 'xxx',
                    client_secret: 'xxx'
                }
            })
            .then((repos)=>{
                console.log(`repos = ${repos}`);
                for (let i = 0; i < repos.length; i++) {
                     console.log(`repos ${i}  = ${repos[i]}`);
                }
            });
        }else{
            console.log(`e.keyCode = ${e.keyCode}`);
        }
    });
})();
<input _ngcontent-inf-0="" class="form-control" id="searchUser" placeholder="Github username..." type="text">

查看更多
若你有天会懂
6楼-- · 2018-12-31 09:33

Using TypeScript, and avoid multiples calls on the function

let el1= <HTMLInputElement>document.getElementById('searchUser');
el1.onkeypress = SearchListEnter;

function SearchListEnter(event: KeyboardEvent) {
    if (event.which !== 13) {
        return;
    }
    // more stuff
}
查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 09:34
<div class="nav-search" id="nav-search">
        <form class="form-search">
            <span class="input-icon">
                <input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
                <i class="ace-icon fa fa-search nav-search-icon"></i>
            </span>
            <input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
        </form>

</div>

<script type="text/javascript">
    $("#search_value").on('keydown', function(e) {
        if (e.which == 13) {
             $("#search").trigger('click');
            return false;
        }
    });
    $("#search").on('click',function(){
        alert('You press enter');
    });
</script>
查看更多
登录 后发表回答