How to prevent user from typing in text field without disabling the field?

前端 未结 11 1687
不思量自难忘°
不思量自难忘° 2021-01-31 06:58

I tried:

$(\'input\').keyup(function() {

   $(this).attr(\'val\', \'\');

});

but it removes the entered text slightly after a letter is enter

11条回答
  •  长发绾君心
    2021-01-31 07:29

    One option is to bind a handler to the input event.

    The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).

    Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.

    This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the input event is received.

    const inputEl = document.querySelector('input');
    
    inputEl.addEventListener('input', (event) => {
      event.target.value = '';
    });

    Tested in Safari 10, Firefox 49, Chrome 54, IE 11.

提交回复
热议问题