I have created a live search, I want when user clicks on ESC it should focus to input box and remove its content if not empty automatically.
I am able to remove the content but it won't focus on key press.
The function focus();
works when I use it on window.onload
I have the existing code: (also tried the ones maked in comment thanks to Focus Input Box On Load, and JavaScript set focus to HTML form element)
var aramaAlani = document.getElementById("id_arama");
$( document ).on( 'keydown', function ( e ) {
if ( e.keyCode === 27 ) { //ESC key code
aramaAlani.reset();
aramaAlani.focus();
//aramaAlani.scrollIntoView();
//document.forms[ 'id_arama' ].elements[ _element ].focus();
//document.getElementById("id_search").focus();
}
});
Is there any specific method for key events to focus on element?
You can't call
clear
function oninput
.You have 2 options:
Clear the specific input using
input.value = '';
Like this:
Or you can use the method
reset()
but you can call it only onform
element. The good point in this solution is if you want to clear many inputs.Like this: