1

I currently have a button with an onclick attribute, directing to a JS function. After I click it with my mouse, pressing the Enter key clicks the button as well, which I want to disable. My button:

<button onclick = "action()">Button</button>

My JS function:

function action(){
//do something
}

I tried solutions from Disable Enter Key and Disabling enter key for form, but they don't work. How do I solve this? Should I not use onclick? I would like a solution in pure JS.

  • Sry, but this is still far from enough information to understand what's going on in your code. Like, it may be relevant what this `//do something` is. Then the default type for ` – Thomas Apr 03 '21 at 21:28
  • @Thomas I made a quick codepen: https://codepen.io/Crypt1111/pen/bGgWmLr. Like if you press the button with your mouse, then if you press Enter, it still clicks, which I want to disable. – SomeRandomCoder Apr 03 '21 at 21:37

2 Answers2

0

You could have an event listener listening for a keydown event and check if it's the enter key and the target your button. In that case disable the event.

Something like this should work, you can add the correct type:

window.addEventListener('keydown',(e) => {  
  if (e.keyIdentifier =='U+000A' || e.keyIdentifier =='Enter' || e.keyCode == 13)
    if (e.target.nodeName=='BUTTON' && e.target.type=='') {
      e.preventDefault()
      e.stopPropagation()
      return false
  }
}, true);
Flip
  • 6,233
  • 7
  • 46
  • 75
  • Thank you for your reply, but it is not working. The problem I am trying to fix is that let's say you click the button once with your mouse, but then if you press the Enter key, it will continually click the button. @Flip – SomeRandomCoder Apr 03 '21 at 13:14
  • 1
    But @SomeRandomCoder that's a different problem/question than what you've asked. – Thomas Apr 03 '21 at 13:56
  • @SomeRandomCoder I agree with Thomas, please be more specific what you want and consider accepting the answer, if it solves the problem that is described in the question. – Flip Apr 03 '21 at 14:11
  • @Thomas Sorry for the misunderstanding. I edited the question. – SomeRandomCoder Apr 03 '21 at 20:50
0

try setting the button to .blur() or set focus to another element

<button onclick = "action();">Click this</button>

function action(){
    //do something
    this.blur()
}
Jim Kolb
  • 21
  • 5