How to trigger back space with jQuery?

I have the below code which triggers various events on keydown

    $('#input-div').keydown(function(e) {
if(e.which == 13) {
    userInput = $(this).val();
    $(this).val(userInput.substring(0,0));

this clears up input box. But since the enter key is pressed, the cursor goes to the second line. I want the cursor to go back to the initial position after the enter key is released; on key up.

any help?

Answers 1

  •     <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <script
        src="https://code.jquery.com/jquery-3.1.1.min.js"
        integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
        crossorigin="anonymous"></script>
    </head>
    <body>
      <form method="POST" id="userform">
          <input type="text" name="firstname" id="firstname">
          <input type="text" name="lastname" id="lastname">
      </form>
    
      <script type="text/javascript">
        $("#userform").submit(function(e){
           return false;    
       });
    
        $("#userform input").keydown(function(e) {
            if(e.which == 13) {
                userInput = $(this).val();
                $(this).val(userInput.substring(0,0));
                $("#userform input#firstname").focus();
            }    
        });    
    </script>
    </body>
    </html>
    

    you may use .focus() to focus on specific input box


Related Articles