While I was building the blog system for this website I was looking for some Javascript that would read a textarea and generate random tags from it, but I couldn't find one and decided to make one.
While I was building the blog system for this website I was looking for some Javascript that would read a textarea and generate random tags from it, but I couldn't find one and decided to make one myself. Hopefully this will come in use for other people, Feel free to make it better and share with other people.
For this script to work you will need to download jQuery from http://jquery.com.
This function is used to see if the passed array contains the passed value, if it does, it will return true. This is used later on to remove duplicates.
function contains(arr, val)
{
for(j=0; j<arr.length; j++) if(arr[j]==val)return true;
return false;
}
This next function is the function that removes the duplicates.
function uniqueArr(arr)
{
temp = new Array();
for(i=0; i<arr.length; i++)
{
if(!contains(temp, arr[i]))
{
temp.length+=1;
temp[temp.length-1]=arr[i];
}
}
return temp;
}
Now onto the final function, this function is the one that generates the random tags and places the tags into the selected form field.
function genTags(arr, numTags, myField)
{
myTags = new Array();
num = 0;
for ( var i in arr )
{
var randomWord = arr[Math.floor(Math.random()*arr.length)];
if (!contains(myTags, randomWord) && num < numTags)
{
myTags[num] = randomWord;
num++;
}
}
$(myField).val(myTags.join(", "));
}
Now, here's the final bit of the code, the code that makes everything work.
$(document).ready(function(){
var fromField = "#content"; // The field where the tags come from
var toField = "#tags"; // The field where tags get put
var maxNumTags = 10; // maxium number of tags
$(fromField).keyup(function()
{
var regxp = /[^a-zA-Z 0-9']+/g;
var myText = $.trim($(fromField).val()).replace(regxp,"");
var myWords = new Array();
var myWords = myText.split(' ');
var uniqueWords = uniqueArr(myWords);
genTags(uniqueWords, maxNumTags, toField);
});
});
There's one thing you might want to do though, You might want to strip out any HTML from the tags, but I will leave that to you.
Try the demo here : http://paulparadise.co.uk/demos/javascript/tag-generator.html