Igor Alex
Igor Alex

Reputation: 1121

How to disable enter press in <Select> field?

I have this element:

<Select>
  <Option value='1'>1</Option>
  <Option value='2'>2</Option>
</Select>

I want to disable form submission when Enter is pressed. I tried the following with <Input> field:

<Input onPressEnter={disableEventHelper} />

disableEventHelper = (e) => e.preventDefault();

But, for some reason, this didn't work for <Select> Is there is another way to do this?

Upvotes: 1

Views: 2472

Answers (1)

Christian LSANGOLA
Christian LSANGOLA

Reputation: 3307

Try code snippet in your Javascript code:

window.addEventListener('keydown',function(event){
  if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
});

However, if you only want to target your form, then do the following:

Say your form has a class called your-form:

const form = document.querySelector('.your-form');

form.addEventListener('keydown',function(event){
  if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
});

Upvotes: 5

Related Questions