Search code examples
jquerydigit

Jquery control input field


How can Jquery control input type="text" 4 digit, if user type 5 digit, the first one will remove to keep 4 digit ?

for example: input > A001

if input > A0015, change to 0015, the first digit will auto remove


Solution

  • Add an input event to your input text element and check its length on each input and if its greater than 4 use substring to remove 1st character.

    $('input').on('input',function(){
       var val=this.value;
         if(val.length>4)
            this.value=this.value.substring(1);
    })
    

    DEMO

    Simpler version

    $('input').on('input',function(){
       this.value=this.value.length>4?this.value.substring(1):this.value;
    })
    

    DEMO