简体   繁体   中英

How to prevent 'pressing enter' in an input to trigger an event ? Java script

I have an input and an appended button. The click on button calls some function. But I don't want this function to be called when user 'presses enter key'. On the other hand, I want on keyup in this input to call some other function. SO I put

$(document).on('keyup', '#id', function(e){
        call();//calling some function
        if (e.which == 13 || event.keyCode == 13) {
            e.preventDefault();//I also tried to return false
        }
     });

But it doesn't seem to work, someone has an idea ?

$(document).on('keyup', '#id', function(e){
    if (event.keyCode != 13) {
        e.preventDefault();
        call();//calling some function
    }
    return false;
 });

Try this:

$(document).on('keyup', '#id', function(e){
    if (e.which == 13 || e.keyCode == 13) {
        e.preventDefault();//I also tried to return false
    }else{
         call();//calling some function
    }
 });

不要使用keyup,因为表单是在keydown上发送的。

Have you tried switch .call() function to a simple alert(), just for tests purpose. @Oyeme and @Jai code seems to work properly.

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