javascript – why can't I type enter instead of heving a button?-ThrowExceptions

Exception or error:

I have an input textbox in HTML, and I would like that when I press ENTER on the specific input, it performs a function:

<input type="text" placeholder="English" id="englinput" onkeypress="enterEvent()">

How should my javascript code look to perform something like this:

function enterEvent() {   
   document.getElementById('btnport').style.visibility = 'visible'; 
   document.getElementById('btnstart').style.visibility = 'hidden';
} 
How to solve:

onkeypress is passing an event object, you probably have to mute default submitting of the form with event.preventDefault().

function enterEvent(event) {
   event.preventDefault()  
   document.getElementById('btnport').style.visibility = 'visible'; 
   document.getElementById('btnstart').style.visibility = 'hidden';
} 

You can use if (event.which === 13 || event.keyCode === 13) inside to add a custom action for ENTER key.

###

To be able to detect the Enter key, you need to capture the event, so the attribute onkeypress should be: onkeypress="enterEvent(event)"

Then, in your javascript code you need to validate that key event:

function enterEvent(event){
    if(event.keyCode === 13){
        event.preventDefault();

        document.getElementById('btnport').style.visibility = 'visible';
        document.getElementById('btnstart').style.visibility = 'hidden';
    }
}
#btnport { visibility: hidden }
<input type="text" placeholder="English" id="englinput" onkeypress="enterEvent(event)">

<button id="btnport">Port</button>
<button id="btnstart">Start</button>

Leave a Reply

Your email address will not be published. Required fields are marked *