We've all used textarea boxes before, so I thought I'd share a few functions I recently created.
The first two functions were solutions to a requirement where I had to convert the text within a textarea box to render within a div or span element. At first I thought it would be easy, a simple div.innerHTML = textarea.value but then another problem showed up. All text were rendered by the browser as one paragraph. Thus I needed a new line to <br /> converter. The last two function automatically grows a textarea box vertically as a user inputs content larger than the original size, it also takes a second argument that limits the amount of characters, good for client side validation.
The first function is a common block that's been around the web for a while now, but all the versions break down to either this function below or just replacing references to /n (text.replace(re_nlchar,'<br />')). This function converts all new lines or \n to the hml tag <br />
/* Converts any new line to <br/> */
function nl2br(text){
text = escape(text);
var re_nlchar;
if(text.indexOf('%0D%0A') > -1){
re_nlchar = /%0D%0A/g ;
}else if(text.indexOf('%0A') > -1){
re_nlchar = /%0A/g ;
}else if(text.indexOf('%0D') > -1){
re_nlchar = /%0D/g ;
}
return unescape( text.replace(re_nlchar,'<br />') );
}
This function finds all textarea with the supplied classname. Runs the text through nl2br function and then replaces the parent layer with the formatted text
** Note that each textarea must each have a div or span layer encapsulating the element, this is where the newly formatted text will be dumped in
function convertTextAreaToHTML(className,textareasContainer)
{
boxes = getElementsByClassName(className,document.getElementById(textareasContainer));
for (x = 0; x<boxes.length; x++)
{
boxes[x].parentElement.innerHTML= nl2br(boxes[x].value);
}
} You may have seen this feature many times before, it automatically grows a textarea box vertically as a user inputs content larger than the original size. It also takes a second argument to limit the amount of characters entered. Good for client side validation.
/* Automatically enlarges a textarea box as user typse */
function grow(ele,limitnum) {
if (ele.scrollHeight > ele.clientHeight && !window.opera)
{
ele.rows += 1;
ele.style.height=ele.clientHeight+20;
}
if (limitnum != undefined)
limitText(ele,limitnum);
else
limitText(ele,1800);
}
/** SF: limits the amount of characters in a textarea box based on sent in param.*/
function limitText(item,limitNum) {
if(limitNum == undefined){
limitNum = 55;
}
if (item.value.length > limitNum) {
item.value = item.value.substring(0, limitNum);
alert('Note that your input has been clipped to only '+limitNum+' characters');
}
}