-1

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';
} 
Mahatmasamatman
  • 1,537
  • 2
  • 6
  • 20
Isaac
  • 65
  • 1
  • 8

2 Answers2

2

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.

Deykun
  • 1,298
  • 9
  • 13
1

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>
blex
  • 24,941
  • 5
  • 39
  • 72
jalamprea
  • 136
  • 8
  • Thanks, it works. but I wnat now the function to call anther function, but it doesn't work. I did it like that: ```` function enterEvent(event){ if(event.keyCode === 13){ event.preventDefault(); return function (test()) } } ```` but it gives an error – Isaac Feb 26 '20 at 00:36
  • you have a bad return.. so, instead of `return function (test()) ` just call the function or return it directly: `return test()` – jalamprea Feb 26 '20 at 19:43