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>
2
Answers
The issue is because you’ve nested the
keydown
event handler within thechange
event. Nesting event handlers is rarely a good thing to do. Use a singlekeydown
event handler:That being said, a better approach entirely would be to wrap your
input
in aform
element and put therequired
attribute on it. That way you don’t need any JS at all: