Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing the Enter key to cause a button click with javascript

i want to Capturing the Enter key to cause a button click

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 is work fine with IE browser but it didn't with Firefox,

Why ? can anybody fix this javascript code to work on all browsers.

thank you

like image 222
Swell Avatar asked Dec 10 '22 12:12

Swell


2 Answers

You should really not use inline 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 then look like this:

<input type="button" id="submit" value="Search"/>
<input type="text" name="search" id="search" />
like image 173
Jacob Relkin Avatar answered Dec 21 '22 23:12

Jacob Relkin


I'd suggest using the keydown event instead for this particular case, since it simplifies key detection: you can use keyCode in all browsers. Also, you're passing in the ID of the button you want to click but then not using it, so I've changed that. Also, I've added a return false to prevent the default behaviour of pressing the enter key, (although this part won't have any effect in Opera: you'll need to suppress the keypress event instead in that browser):

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;
        }
    }

}

like image 28
Tim Down Avatar answered Dec 21 '22 22:12

Tim Down