Search code examples
javascripteventsonkeyup

Call javascript function on enter of a text input, without using jquery


Is it possible to call a javascript function on enter of a text input, without using jquery?

<input name = 'text' type = 'text' onEnter('callJavascriptFunction')> 

^---it would be preferable for the onEnter to be inside the element like above...


Solution

  • Sure is:

    <input name="text" type="text" onkeyup="callJavascriptFunction();">
    

    You can also do it without the inline javascript:

    <input id="myTextBox" name="text" type="text">
    

    Then in your js file:

    var myTextBox = document.getElementById('myTextBox');
    myTextBox.addEventListener('keyup', function(){
        //do some stuff
    });
    

    Edit: If you're looking for enter press:

    <input id="myTextBox" name="text" type="text">
    

    Then in your js file:

    var myTextBox = document.getElementById('myTextBox');
    myTextBox.addEventListener('keypress', function(){
        if(e.keyCode == 13){//keyCode for enter
            //do some stuff
        }
    });