Search code examples
javascriptjquerysplitcountlimit

How to count specific elements and limit number of them with jQuery/JS


For example:

string/text field = "United, Arsenal, Chelsea"

I need to allow only 3 clubs entered in text field separated by ",", if user try to enter fourth club it needs to ignore it and allow only removing of existing clubs and writing new instead of some existing.

I've done it but when i try to enter fourth club it comes to return false or preventDefault and stops there, i can't do anything (remove existing club or any of them)...


Solution

  • You can do it like this:

    $(document).on('ready', function() {
    
      $("#sportsText").on("input", function(e) {
    		var str = $(this).val();
    	  
    	  var comma_count = (str.match(/,/g) || []).length;
    	  
    	  if(comma_count > 2)
    	  {
    	  	$(this).val(str.substring(0, str.length - 1));
    	  }
    	})
      
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="myDiv">
      <input id="sportsText" type="text">
    </div>

    Also view it on - jsFiddle

    Hope this helps!