Trigger a button click with JavaScript on the Enter key in a text box

后端 未结 30 1959
难免孤独
难免孤独 2020-11-21 23:53

I have one text input and one button (see below). How can I use JavaScript to trigger the button\'s click event when the Enter key is pressed ins

30条回答
  •  悲哀的现实
    2020-11-22 00:45

    Nobody noticed the html attibute "accesskey" which is available since a while.

    This is a no javascript way to keyboard shortcuts stuffs.

    The accesskey attributes shortcuts on MDN

    Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser

    let client = navigator.userAgent.toLowerCase(),
        isLinux = client.indexOf("linux") > -1,
        isWin = client.indexOf("windows") > -1,
        isMac = client.indexOf("apple") > -1,
        isFirefox = client.indexOf("firefox") > -1,
        isWebkit = client.indexOf("webkit") > -1,
        isOpera = client.indexOf("opera") > -1,
        input = document.getElementById('guestInput');
    
    if(isFirefox) {
       input.setAttribute("placeholder", "ALT+SHIFT+Z");
    } else if (isWin) {
       input.setAttribute("placeholder", "ALT+Z");
    } else if (isMac) {
      input.setAttribute("placeholder", "CTRL+ALT+Z");
    } else if (isOpera) {
      input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");
    } else {'Point me to operate...'}

提交回复
热议问题