Keyup () is not working?

2

I have a function that is supposed to show how many characters are missing to reach the maximum, however, it only counts after the first key is "clicked".

Here's my code

$("#nome_event").keyup(function(){
  var count = $(this).length;
  var dif = 30 - count;
  $("#count_nome2").html(count);
  if(count < 30 ){
    $("#count_nome").html(dif);
  }
});
<div class="form-group">
   <label>Nome do Evento</label>
   <input class="form-control" id="nome_event">
   <p class="help-block"><small>[<span id="count_nome">30</span> | <span id="count_nome2">30</span> Caracteres por usar]</small></p>
</div>
    
asked by anonymous 14.11.2017 / 17:31

1 answer

3

.val() was missing from:

var count = $(this).val().length;

$("#nome_event").keyup(function(){
  var count = $(this).val().length;
  var dif = 30 - count;
  $("#count_nome2").html(count);
  if(count < 30 ){
    $("#count_nome").html(dif);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="form-group">
   <label>Nome do Evento</label>
   <input class="form-control" id="nome_event">
   <p class="help-block"><small>[<span id="count_nome">30</span> | <span id="count_nome2">30</span> Caracteres por usar]</small></p>
</div>

When you put $(this).length; you will only count the number of elements with id specified, not the length size of your content.

    
14.11.2017 / 17:38