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

Time:02-01

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  placeholder="Type something then press 'Enter' key." />
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

CodePudding user response:

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  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  required placeholder="Type something then press 'Enter' key." />  
    <button type="submit">Search</button>
  </form>
</div>

CodePudding user response:

$('.tag-input').bind('keyup',function() {            
        alert(this.value);
});
.tag-input{
  width:80%;
 }
<div >
    <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>

  • Related