utdev
utdev

Reputation: 4102

Javascript add letter after specific number of letters in a loop

I am trying to add a br sign in a input text field if it has more than 5 letters.(while writing)

My Code creates br signs after 5 letters, but it creates for than 1 br sign.

Code:

(function(i){
    $('#input' + i).on('keyup', function() {
        if($('#input' + i).val().length > 5) {
            $('#input' + i).val($('#input' + i).val() + '<br>');
        }
    });
}(i))

Upvotes: 0

Views: 406

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074276

I strongly recommend not doing this (seem comments on the question).

But if you really want to, use input, not keyup, remove previous <br> markers you've added, and break up the whole string rather than just appending at the end. See comments:

(function(i) {
  $('#input' + i).on('input', function() {
    // No need to look it up repeatedly, remember the jQuery wrapper for this input
    var $this = $(this);
    // Get the value
    var val = $this.val();
    if (val.length > 5) {
      // Remove old <br>s
      val = val.replace(/<br>/g, "");
      // Add new ones
      var result = "";
      while (val) {
        result += val.substring(0, 5);
        val = val.substring(5);
        if (val) {
          result += "<br>";
        }
      }
      // Set the value
      $this.val(result);
    }
  });
}(0))
<input type="text" id="input0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions