Capture Enter key to trigger button click using javascript

I want to capture the Enter key to call a button

I have this javascript:

    function doClick(buttonName,e)
    {
        //the purpose of this function is to allow the enter key to 
        //point to the correct button to click.
        var key;

         if(window.event)
              key = window.event.keyCode;     //IE
         else
              key = e.which;     //firefox

        if (key == 13)
        {
            //Get the button the user wants to have clicked
            var btn = document.getElementById('submit');
            if (btn != null)
            { //If we find the button click it
                btn.click();
                event.keyCode = 0
            }
        }
   }

with html

<input type="button" id="submit" value="Search" onClick="doSomeThing();" />
<input type="text" name="search" onKeyPress="doClick('submit',event)" />

this works fine with IE browser, but not with Firefox,

Why? can someone fix this javascript code to work in all browsers.

Thank you

+3
source share
4 answers

You really shouldn't use the built-in event handlers:

window.onload = function() {
   document.getElementById('submit').onclick = doSomething;
   document.getElementById('search').onkeypress = function(e) {
       doClick('submit', e);
   };
};

function doClick(buttonName,e)
{
  //the purpose of this function is to allow the enter key to 
  //point to the correct button to click.
  var ev = e || window.event;
  var key = ev.keyCode;

  if (key == 13)
  {
     //Get the button the user wants to have clicked
     var btn = document.getElementById(buttonName);
     if (btn != null)
     { 
        //If we find the button click it
        btn.click();
        ev.preventDefault(); 
     }
  }
}

Your HTML should look like this:

<input type="button" id="submit" value="Search"/>
<input type="text" name="search" id="search" />
+7
source

keydown , : keyCode . , , , , . , return false, ( Opera: keypress )

function doClick(buttonId, e)
    {
    if (e.keyCode == 13)
        {
        // Get the button the user wants to have clicked
        var btn = document.getElementById(buttonId);
        if (btn)
        {
            btn.click();
            return false;
        }
    }

}

+5

js framework, jQuery? - . (-, , ):

jQuery(function(){
  jQuery(window).keyup( function(e){ 
    if (e.keyCode == 13) {
      // handle click logic here
    }
  });
});
+2

OnKeyDown

if (event.keyCode == 13) {
    document.getElementById('submit').click(); 
    return false;
}
0

Source: https://habr.com/ru/post/1778567/


All Articles