3

I got an input field that displays a bootstrap tooltip when focused.

<input id="nombrecurso" name="nombrecurso"
                        data-original-title="Required field!"
                        data-toggle="tooltip" data-trigger="hover"
                        data-delay='{"show":"200", "hide":"0"}'
                        class="form-control input-lg">
<h6 class="count_message pull-right"></h6>

The Number of characters remaining for that field is displayed in a near <h6>. This counter is updated on a jquery keyup event.

$(document).ready(function() {
  $('[data-toggle="tooltip"]').tooltip();
});
$(document).on("keyup", '#nombrecurso' ,function() {
  $(this).next('.count_message').empty().append($(document.activeElement).attr('maxlength') + ' characters remaining');
  //event code, is doesn't have to be keyup, it happens with 
  //other events such as click

}

The problem is when the tooltip is active, the jquery event keyup doesn't fire up and the counter is not updated.

You can see the problem here: codepen.

Try to write something in the input with and without the mouse over the input field.

...Any ideas how to fix this?

40detectives
  • 350
  • 1
  • 3
  • 12

1 Answers1

1

The tooltip dynamically inserts an element after the input, so that next() will not match your output element. Use nextAll() instead:

e.g.

$(this).nextAll('.count_message')

CodePen: http://codepen.io/HiTechMagic/pen/NGJJwY

notes:

  • Inside the keyup handler, you can use $(this) and not $(document.activeElement).
  • Rather then empty().append() use html() to set text content (use empty() & append() with DOM elements to avoid re-parsing HTML).

e.g.

$(document).ready(function() {
  $('[data-toggle="tooltip"]').tooltip();
});

$(document).on("keyup", '#nombrecurso', function() {
  var text_length = $(this).val().length;
  var whatareyoucounting = $(this).attr('maxlength');
  var text_remaining = whatareyoucounting - text_length;
  $(this).nextAll('.count_message').html(text_remaining + ' characters remaining');
});
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • Wow, it was so evident I cant belive i missed so much time with it :$ ...THANK YOU. – 40detectives Nov 19 '15 at 17:48
  • Took me 10 minutes playing about to figure it out, as debugging a `tooltip`, that vanishes as soon as you move to the DOM inspector, is not easy :) – iCollect.it Ltd Nov 19 '15 at 17:50
  • Is really recommendable to use html() over .empty().append() ? – 40detectives Nov 19 '15 at 17:53
  • 1
    Does the same thing in one operation *for text*. If you were adding DOM elements you would use `append`, but this is plain text (so the parsing overhead is the same). Clarified that note for you. – iCollect.it Ltd Nov 19 '15 at 17:54