0

I want to add a sign in an input text field while writing,

if the field extends 20 sign / letters.

How do I accomplish this

So far I tried this:

    (function(i){
        $('#input-chapter-name' + i).change(function(){
            if($(this).val().length() > 20) {
                $(this).val($this.val() + '<br>');
            }
        })
    }(i))

Thus I get this error in my console:

Uncaught TypeError: (intermediate value)(...) is not a function(…)

utdev
  • 3,942
  • 8
  • 40
  • 70
  • It looks like you are checking if the input value is less than 20 chars, shouldn't you have something like `if($('#input-name' + i).val().length > 20)` – Saleh Dec 06 '16 at 10:14
  • Whops I Made an edit – utdev Dec 06 '16 at 10:15
  • You have tried calling `val().length()` when it should be used as a property like this `val().length` that might resolve your recent error. – Saleh Dec 06 '16 at 11:52
  • `$this.val()` doesn't look right either it should be `$(this).val()`. – Saleh Dec 06 '16 at 12:04
  • Possible duplicate of [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – utdev May 23 '18 at 19:09

3 Answers3

0

Create something like this:

HTML

<label>+</label><input type="number">

CSS

input {
  padding-left: 20px;
}
label {
  position: relative;
  left: 15px;
}

It'd look something like: enter image description here

JsFiddle: https://jsfiddle.net/jshacker/w53kkrh8/


What you need is though, css classes so that you can add it when the length increases a certain limit. Follow Ahmed's answer.


Also, note while accepting numbers with 20 digits:

There is a problem with number size. JavaScript numbers cannot be 20 digits in length. You have to use strings to represent big numbers.

0

You need to check for the input value length not the element length:

(function(i){
        if($('#input-name' + i).val().length > 20) {
            $('#input-name' + i).val($('#input-chapter-name').val() + '<br>');
        }
    }(i))
Saleh
  • 150
  • 10
0

Below is a generic implementation, it will add/remove a class on the field according to the current length

HTML

<input type="text" warn-max-length="20" />

JavaScript

$(function(){
  $('[warn-max-length]').on('change', function() {
     var $this = $(this);
     var max = $this.attr('warn-max-length');

     // toggle 'max-length-exceeded' class
     $this[$this.val().length >= max ? 'addClass' : 'removeClass']('max-length-exceeded');
  })
})

Highlights

  • Use on input instead of keyup/keydown event listener to handle copy/paste cases

  • Manage the UI changes in CSS if possible i.e input.warn-max-length { color: red; }

amd
  • 20,637
  • 6
  • 49
  • 67