jQuery .val() ignoring first character of input

Viewed 315

I have an input and a label. I want to show the label when the user types anything in the input box. However, as you can see in the snippet (or on jsFiddle), the first character you type in the input box is ignored and you need to type another one in order for the value to not be empty.

$('input').on('change paste keydown', function(event) {
    var inputID = event.target.id;
    var value = $('#' + inputID).val();
    $('#' + inputID + 'Label').css('visibility', 'visible');   

    if (value == ''){
        $('#' + inputID + 'Label').css('visibility', 'hidden');
    }
})
#input1Label { visibility: hidden; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id='input1Label'>Label</label>
<input id='input1'>

2 Answers

Listen for input instead.

keydown, as its name implies, triggers before the key is lifted and, crucially for you, before the value is updated.

input not only has the benefit of covering all three of the events you're currently listening for, but also fires after the value is updated, meaning you'll get the latest value.

$('input').on('input', event => {
    let inputID = event.target.id;
    $('#'+inputID+'Label').css('visibility', $('#'+inputID).val() ? 'visibile' : 'hidden');
})

keydown is triggered before the value of the input changed thats why you are getting an empty value for the first time.

You should change it to keyup event, which is triggered after the key is released.

$('input').on('change paste keyup', function(event) {
  var inputID = event.target.id;
  var value = $('#' + inputID).val();
  $('#' + inputID + 'Label').css('visibility', 'visible');

  if (value == '') {
    $('#' + inputID + 'Label').css('visibility', 'hidden');
  }
})
#input1Label {
  visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id='input1Label'>Label</label>
<input id='input1'>

Related