Javascript Event How to - Handle enter key event








Question

We would like to know how to handle enter key event.

Answer


<html>
<body>
  <input type="text" id="url" />
    <script type='text/javascript'>
    <!--from w w  w . j  a  v a 2  s . c  om-->
    var input = document.getElementById('url');
    input.onkeydown = function(e) {
      var key = e.keyCode || e.which;
        if (key == 13) {
           console.log("enter");
           window.location = input.value;
        }
    };
    </script>

</body>
</html>

The code above is rendered as follows: