0

In jQuery I get the value using following code:

$('#input_id').keypress(function(){ 
  var content= $(this).val(); alert(content);
});

In this case I type 'a' it alerts blank and I type 'ab' it alerts 'a'. Is any idea for when I type 'a' it should alert 'a' and when I type 'ab' it should alert 'ab'?

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34

3 Answers3

1

You need to use on("keyup" or on("input" since keypress is fired before the value is added to the field. You also use alert which blocks all further processing

$('#input_id0').on("keypress",function() {
  var content = $(this).val();
  console.log(content);
});
$('#input_id1').on("keyup",function() {
  var content = $(this).val();
  console.log(content);
});
$('#input_id2').on("input", function() {
  var content = $(this).val();
  console.log(content);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input_id0" placeholder="keypress" /><br/>
<input id="input_id1" placeholder="keyup" /><br/>
<input id="input_id2" placeholder="input" /><br/>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You can use keyup instead of keypress function:

$(document).ready(function() {
  $('#input_id').keyup(function(){ 
   var content= $(this).val(); alert(content); 
  });
});
a
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type='text' id='input_id'>
Ankur Mishra
  • 1,284
  • 1
  • 6
  • 15
0

That's because you're working with keypress event. Instead, you should use keyup to achieve your requirement.

$('#input_id').keyup(function() {
  var content = $(this).val();
  alert(content);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input_id">
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34