Keyup() not working?

Asked

Viewed 210 times

2

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

Here is 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>

1 answer

3


Missed the .val() in:

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>
<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>

When placing $(this).length; only the number of items with the id specified, not the size length of its contents.

  • It worked perfectly, but it might explain why it only worked on the first?

  • 1

    @I_like_trains When you put $(this).length; it actually counts the number of elements with the id, which has only one. The .val().length counts the size of the content inside the element.

  • Thanks for the clarification!

  • @I_like_trains Dispo, amigo!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.