How to add new value on keyup to div every n digit with jquery?

  html, javascript, jquery

I want to auto list numbers every time the user types in 3 digits. The input numbers should appear in the div automatically.

$("#lister").on("keyup", function() {
  var mxlen = $(this).data("mxlen");
  var input = $(this).val();
  if (input.length == mxlen) { //if input==3
    $('#num_list').append('<li>' + input + '</li>');
    $(this).html(''); //clear input after appended
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="num_list"></div>
<input type="number" id="lister" data-mxlen="3" />

The problem with my code is that it repeats the same numbers and does not clear the input after appending.

Source: Ask Javascript Questions

LEAVE A COMMENT