Focus Input Box On Key Pressed

前端 未结 1 1760
暖寄归人
暖寄归人 2021-01-26 18:36

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 cont

相关标签:
1条回答
  • 2021-01-26 19:20

    You can't call clear function on input.

    You have 2 options:

    Clear the specific input using input.value = '';

    Like this:

    <body>
      <input type="text" id="id_arama" />
      <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
      <script>
        var form = document.querySelector('form');
        var aramaAlani = document.getElementById("id_arama");
    
        $( document ).on( 'keydown', function ( e ) {
          if ( e.keyCode === 27 ) { //ESC key code
            //form.reset();
            aramaAlani.value = '';
            aramaAlani.focus();     
            //aramaAlani.scrollIntoView();
            //document.forms[ 'id_arama' ].elements[ _element ].focus();
            //document.getElementById("id_search").focus();
          }
        });
      </script>
    </body>

    Or you can use the method reset() but you can call it only on form element. The good point in this solution is if you want to clear many inputs.

    Like this:

    <body>
      <form>
        <input type="text" id="id_arama" />
      </form>
      <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
      <script>
        var form = document.querySelector('form');
        var aramaAlani = document.getElementById("id_arama");
    
        $( document ).on( 'keydown', function ( e ) {
          if ( e.keyCode === 27 ) { //ESC key code
            form.reset();
            aramaAlani.focus();     
            //aramaAlani.scrollIntoView();
            //document.forms[ 'id_arama' ].elements[ _element ].focus();
            //document.getElementById("id_search").focus();
          }
        });
      </script>
    </body>

    0 讨论(0)
提交回复
热议问题