简体   繁体   中英

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!

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"

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM