Kaisin Li
Kaisin Li

Reputation: 544

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!

Upvotes: 4

Views: 11792

Answers (3)

Muthu Kumaran
Muthu Kumaran

Reputation: 17930

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"

Upvotes: 6

brk
brk

Reputation: 50346

You need to use keyup as keypress will trigger value as soon as a key is pressed which is separate from releasing a key.

There are few changes that can be done. input is a self closing tag. Also it is better to use $(this) inside the function as it will get the value only from the input from where the event is triggered.

There may be a catch here. On pressing enter/return key you may see the form is getting submitted

$(document).ready(function() {
  $("input").keyup(function(e) {
    var currentInput = $(this).val();
    console.log(currentInput);
    if (e.keyCode == 13) {
      console.log('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>

Upvotes: 0

Dan Barbarito
Dan Barbarito

Reputation: 480

The keypress function fires right as a key is pressed. You want to use keyup as that will fire when the key is released.

Upvotes: 0

Related Questions