简体   繁体   中英

Jquery does not work for the first click on the enter key in an html input

I want when a user type something in an input, after pressing enter key, the jquery do something. I am using the following code, but there is a problem on the first time pressing enter key. Actually it does not work. What's the problem and how to fix it?

 $('.tag-input').on('change', (e) =>{ $(this).on("keydown", event=> { if(event.which == 13 && $('.tag-input').val().length>0) alert($('.tag-input').val()); }); });
 .tag-input{ width:80%; }
 <div > <input class="tag-input" placeholder="Type something then press 'Enter' key." /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

The issue is because you've nested the keydown event handler within the change event. Nesting event handlers is rarely a good thing to do. Use a single keydown event handler:

 $('.tag-input').on('keydown', e => { const $input = $(e.target); if (e.which == 13 && $input.val().trim().length > 0) console.log($input.val()); });
 .tag-input { width: 80%; }
 <div> <input class="tag-input" placeholder="Type something then press 'Enter' key." /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

That being said, a better approach entirely would be to wrap your input in a form element and put the required attribute on it. That way you don't need any JS at all:

 .tag-input { width: 80%; }
 <div> <form action="/search"> <input class="tag-input" required placeholder="Type something then press 'Enter' key." /> <button type="submit">Search</button> </form> </div>

 $('.tag-input').bind('keyup',function() { alert(this.value); });
 .tag-input{ width:80%; }
 <div > <input class="tag-input" placeholder="Type something then press 'Enter' key." /> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

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-2025 STACKOOM.COM