0

I am working on limiting tags so max will be 5 but for this test I will use 2 however, at the end of the line there is an extra comma left when attempting to add another tag more than the max-allowable. How do I remove that comma?

    <body>
        <input id="input" type="text" />
    </body>

   $("#input").keypress(function(e){
    var value = $(this).val().replace(" ", "");
    var words = value.split(",");

    if(words.length > 2){
        //alert("Hey! That's more than 5 words!");
        e.preventDefault();
    }
});

DEMO: http://jsfiddle.net/BzN5W/2/

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
A Rob
  • 31
  • 8
  • Possible duplicate of [RTrim in javascript](http://stackoverflow.com/questions/8791394/rtrim-in-javascript) – Rasclatt Sep 24 '16 at 20:25

3 Answers3

1

Here, try this :

$("#input").keypress(function(e){
var value = $(this).val().replace(" ", "");
var words = value.split(",");

if(words.length > 5){
    alert("Hey! That's more than 5 words!");

    $('#input').val($('#input').val().substring(0, $('#input').val().length-1));
        e.preventDefault();
}

});

Kinshuk Lahiri
  • 1,468
  • 10
  • 23
0
$("#input").keypress(function(e){
   var value = $(this).val().replace(" ", "");
   var words = value.split(",");
   if(words.length > 5){
      $(this).val(value.slice(0,value.length-1))
      e.preventDefault();
   }
});
Shrijan Tiwari
  • 673
  • 6
  • 17
0

Try this:

    $("#input").keydown(function(e){
      if(e.which === 188 && ($(this).val().match(/,/g) || []).length ==4){
       e.preventDefault();
      }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <input id="input" type="text" />
</body>
Shrijan Tiwari
  • 673
  • 6
  • 17