Search code examples
phpjqueryhtmlmaxlengthdisabled-input

How to prevent User to enter value at maxlength using jQuery


I want that user should not be able to enter text if he has more then 5 comma separated values in input box.

I have reached the value, but not sure. I think maxlength dynamic should do the trick.

I am trying to apply below code, but not working -

require(["jquery"],function($) {
    $("input.toEmail").keyup(function(e){
        var inputEmail = $("input.toEmail").val();
        var count = (inputEmail.match(/,/g) || []).length;  
        if(count >= 5){
            e.preventDefault();
            e.stopPropagation();
        }
    });
});

Solution

  • You can achieve it in this simple way.

    Note:

    • Use split to "Split a string into an array of substrings"
    • Use slice to "extracts parts of a string and returns the extracted parts in a new string"
    • Use join to "returns the array as a string"

    $("input.toEmail").keyup(function(e){
            var inputEmail = $(this).val();
            var strArray = inputEmail.split(/,/g);
         
            if(strArray.length >= 5){
                this.value = strArray.slice(0, 5).join(',');
            }
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input  type="text" class="toEmail"/>