0

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

3
  • 1
    Consider a form with a submit-button Commented Jan 8, 2016 at 19:32
  • @xoxox Obviously...I wouldn't be asking then... Commented Jan 8, 2016 at 19:43
  • 1
    There's no "onenter" event, you've to detect a keyboard event, for example keyup to detect a key press. Then in the handler function check, if ENTER was hit. Notice, that if the input is in a form, the default action is to submit the form when pressing ENTER. In that case you probably have to prevent the default action. Commented Jan 8, 2016 at 19:54

2 Answers 2

6

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
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

...onkeyup executes when ANY key is pressed on the keyboard.
I need onenter, when the enter key is pressed.
@frosty Google is for free
2

Use the event onchange. You can do this on HTML:

<input onchange="fncDoThings()">

And your JS file can be like this:

function fncDoThings() {
    console.log('hello'); //just an example of things to do inside the function
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.