Question

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?

Was it helpful?

Solution

if(characterCode == 13)
{
    return false; // returning false will prevent the event from bubbling up.
}
else
{
    return true;
}

Ok, so imagine you have the following textbox in a form:

<input id="scriptBox" type="text" onkeypress="return runScript(event)" />

In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.

function runScript(e) {
    //See notes about 'which' and 'key'
    if (e.keyCode == 13) {
        var tb = document.getElementById("scriptBox");
        eval(tb.value);
        return false;
    }
}

returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.

NOTE:

It's been pointed out that keyCode is now deprecated. The next best alternative which has also been deprecated.

Unfortunately the favored standard key, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.

Furthermore, while the deprecated warning is quite ominous about keyCode and which, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.

OTHER TIPS

Use both event.which and event.keyCode:

function (event) {
    if (event.which == 13 || event.keyCode == 13) {
        //code to execute here
        return false;
    }
    return true;
};

If you're using jQuery:

$('input[type=text]').on('keydown', function(e) {
    if (e.which == 13) {
        e.preventDefault();
    }
});

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

Detect Enter key pressed on whole document:

$(document).keypress(function (e) {
    if (e.which == 13) {
        alert('enter key is pressed');
    }
});

http://jsfiddle.net/umerqureshi/dcjsa08n/3/

Override the onsubmit action of the form to be a call to your function and add return false after it, ie:

<form onsubmit="javascript:myfunc();return false;" >

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>

if you want to do it using purly java script here is an example that work perfectly

Let's say this is your html file

<!DOCTYPE html>
<html>
  <body style="width: 500px">
    <input type="text" id="textSearch"/> 
      <script type="text/javascript" src="public/js/popup.js"></script>
  </body>
</html>

in your popup.js file just use this function

var input = document.getElementById("textSearch");
input.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        alert("yes it works,I'm happy ");
    }
});

Below code will add listener for ENTER key on entire page.

This can be very useful in screens with single Action button eg Login, Register, Submit etc.

<head>
        <!--Import jQuery IMPORTANT -->
        <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

         <!--Listen to Enter key event-->
        <script type="text/javascript">

            $(document).keypress(function (e) {
                if (e.which == 13 || event.keyCode == 13) {
                    alert('enter key is pressed');
                }
            });
        </script>
    </head>

Tested on all browsers.

So maybe the best solution to cover as many browsers as possible and be future proof would be

if (event.which === 13 || event.keyCode === 13 || event.key === "Enter")

A jQuery solution.

I came here looking for a way to delay the form submission until after the blur event on the text input had been fired.

$(selector).keyup(function(e){
  /*
   * Delay the enter key form submit till after the hidden
   * input is updated.
   */

  // No need to do anything if it's not the enter key
  // Also only e.which is needed as this is the jQuery event object.
  if (e.which !== 13) {
       return;
  }

  // Prevent form submit
  e.preventDefault();

  // Trigger the blur event.
  this.blur();

  // Submit the form.
  $(e.target).closest('form').submit();
});

Would be nice to get a more general version that fired all the delayed events rather than just the form submit.

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;
        }
}

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
}

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">

A little simple

Don't send the form on keypress "Enter":

<form id="form_cdb" onsubmit="return false">

Execute the function on keypress "Enter":

<input type="text" autocomplete="off" onkeypress="if(event.key === 'Enter') my_event()">
<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>

This function preventKey() works regardless of the deprecated browser features.

Only one of the three properties which (deprecated), keyCode (deprecated) or key (problems in IE) has to be present.

https://jsfiddle.net/tobiobeck/z13dh5r2/

JS

function preventKey(event, expectedKey, expectedCode) {
  const code = event.which || event.keyCode;

  if (expectedKey === event.key || code === expectedCode) {
    return true;
  }
  return false;
}

document.getElementById('myInput').addEventListener('keydown', function(event) {

  if (preventKey(event, 'Enter', 13)) {
    event.preventDefault();
  }
});

HTML

<form>
  <input id="myInput">
</form>

Browser Testing

If you want to test different browsers manually comment or uncomment one of the three following event.something lines:

var event = {};
event.which = 13;
//event.keyCode = 13;
//event.key = 'Enter'

if (preventKey(event, 'Enter', 13)) {
  console.log('enter was pressed');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top