Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery keypress enter not working

I tried to use keypress to get an text from to update a text in . My html looks like this:

<p>words words words <i>test</i> more words</p>
<div id="newWord">
   <form>
      <input type="text" placeholder="New Hashtag"></input>
   </form>
</div>

My jQuery looks like this:

$(document).ready(function () {
    $("input").keypress(
        function (e) {
            var currentInput = $("input").val();
            console.log(currentInput);
            if (e.keyCode === 13) {
                console.log('hello');
            }
        }
    );
})

My console log doesn't log on first keypress, how can I help it? Also my "hello" never log. Any ideas why this is happening?

Thanks!

like image 261
Kaisin Li Avatar asked Oct 12 '25 19:10

Kaisin Li


1 Answers

Use keyup event to capture first keyboard char.

$(document).ready(function () {
    $("input").keyup(
        function (e) {
            var currentInput = $("input").val();
            console.log(currentInput);
            if (e.keyCode === 13) {
                console.log('hello');
                alert('hello');
            }
        }
    );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>words words words <i>test</i> more words</p>
<div id="newWord">
  <form>
    <input type="text" placeholder="New Hashtag">
  </form>
</div>
    

Note: Hitting Enter key will submit the form and it will redirect the page. You might not see the console message for "hello"

like image 89
Muthu Kumaran Avatar answered Oct 14 '25 10:10

Muthu Kumaran