Limit text area value and cut the rest
I have a textarea which users can enter some tags. I need to limit 开发者_如何学运维this tags to 20 tags.
Tags could be enterer this way
maytag1,mytag2,mytag3
What i wrote is this function
function limitTags()
{
var tags = $("input[type=text][name=tags]").val()
var tag = $.trim(tags);
var selected = new Array();
/**
* replace the last ','
*/
if(tag.substring(tag.length - 1) == ",")
{
*///tag = tag.replace(tag.length - 1, '');
}
var enteredTags = tag.split(",");
if( enteredTags.length > 20 )
{
//$("input[type=text][name=tags]").val(enteredTags.join(",", enteredTags));
alert("Only 20 Tags allowed");
}
}
The alert works just fine but, after the alert box is gone. i can continiue entering tags till the alert box appears.
What i need is cut the text after the messagebox which was entered also the last ","
I hope i could ask my question clear.
Thanks
You can use the slice
method to cut the array down to 20 entries before setting the value:
$("input[type=text][name=tags]").val(enteredTags.slice(0,20).join(","));
See: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Slice
Intercept "," pressing, and check how many entries the user inserted so far. If he's trying to insert too many entries just prevent further insertions.
$('input[type=text][name=tags]').keyup(function(e) {
if((e.keyCode == 188) && ($(this).val().split(",").length > 19)) {
alert('Only 20 Tags allowed');
}
});
精彩评论