Reputation: 31
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/
Upvotes: 0
Views: 64
Reputation: 693
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>
Upvotes: 0
Reputation: 693
$("#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();
}
});
Upvotes: 0
Reputation: 1500
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();
}
});
Upvotes: 1