I tried:
$(\'input\').keyup(function() {
$(this).attr(\'val\', \'\');
});
but it removes the entered text slightly after a letter is enter
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.