SomeRandomCoder
SomeRandomCoder

Reputation: 31

How to disable Enter key from pressing buttons?

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.

Upvotes: 2

Views: 1471

Answers (2)

Jim Kolb
Jim Kolb

Reputation: 21

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

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

function action(){
    //do something
    this.blur()
}

Upvotes: 0

Flip
Flip

Reputation: 6781

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

Upvotes: 1

Related Questions