Click here to Skip to main content
15,885,032 members
Articles / Programming Languages / Javascript

Javascript for editing a textarea

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
28 Oct 2014CPOL7 min read 17.2K   5   1
Managing html-input in a textarea

Javascript for editing a textarea

You can see this javascript in action on my website: www.nulacomputers.com Just try the textarea editing. But don't click the Send button (unless you really want to comment on the page)!

Content

Javascript for managing html-input in a textarea

html buttons for a textarea to insert a simple tag

html button for a textarea to insert a tag with css class or css id

The textarea with remaining chars

Javascript for managing html-input in a textarea

De textarea element on an html-input-form has a disadvantage. The syntax is: <textarea>initial text</textarea>. With this as coding on a html-page you see an inputfield with inside the inputfield the text 'initial text'. This works fine. But what happens when you want to use that inputfield for html? Suppose the initial text is '<textarea>some text</textarea>'. Then the syntax on the webpage would be: <textarea><textarea>some text</textarea></textarea>. This would confuse the browser. Probably the browser will show '<textarea>some text' in the textarea inputfield and skip everything after the first appearance of '</textarea>'. But this could be different for each browser.

When you see a textarea inputfield on a webpage that allows you to give comments on the page, you often see a different syntax. Html-tags are changed with square brackets. For example <p> becomes [p]. This is acceptable. But sometimes difficult to read.

I created another solution with javascript. With the following javascript you can use html without any changes. How do we do that?

First of all: avoid <textarea>initial text</textarea>.

Change this in: <textarea name="inputfield1"></textarea>.

Change the body tag in: <body onLoad="OnloadFunction()">

Create a javascript function like:

JavaScript
function OnloadFunction()
{
  NulA_Fill_inputfield(); // This should fill all your textareas
  somefunction(); // optional your own other code on Onload.
  some_other_function(); // optional your own other code on Onload.
}

The textarea fields are initialized by the function NulA_Fill_inputfield(). It looks like this:

JavaScript
var NulA_Fill_vars = new Array();
NulA_Fill_vars[0] = "initialising text for inputfield1, completely free if properly escaped to fit in a javascript string"; 

NulA_Fill_vars[1] = "initialising text for inputfield2, completely free if properly escaped to fit in a javascript string"; 

NulA_Fill_vars[n-1] = "initialising text for inputfieldn, completely free if properly escaped to fit in a javascript string"; 

 
function NulA_Fill_inputfield()
{
   document.forms["FormName"].elements.namedItem("inputfield1").value = NulA_Fill_vars[0];
   document.forms["FormName"].elements.namedItem("inputfield2").value = NulA_Fill_vars[1];
   document.forms["FormName"].elements.namedItem("inputfieldn").value = NulA_Fill_vars[n-1];
}

To make this useful, you should have some Content Management System (in php, asp, perl) that can:

  • retrieve a string from a database and put it in a javascript-array;
  • process a string from a webform and store it in the database.

Once you have this, you can use html in your textarea inputfields.

Content

Javascript for managing html-input in a textarea

html buttons for a textarea to insert a simple tag

html button for a textarea to insert a tag with css class or css id

The textarea with remaining chars

html buttons for a textarea to insert a simple tag

When you see a textarea inputfield on a webpage to comment on that page, you often see buttons for html-tags. I was not pleased with how these buttons work. So I created the following javascript for writing html in a textarea.

First of all I put a help-button above the textarea. I use a small blue circle with an H in it. When clicked a help-text appears for inexperienced users. Click it again and the help-text disappears.

At the right of this button there is a second button to get access to the html-edit-buttons. I use an indigo rectangle with EDIT in it. Click it and the edit buttons disappear. Click it again and you have access to the edit buttons. With only one textarea on your form this is trivial. But if you have ten text-area's and a user only needs to edit one of them, it is nice to have this function.

Both buttons work in the same way with a javascript-event:

onclick="javascript:return NulA_CMS_switch_on_off('element_id')

element_id is the id of a div-element you want to make visible or invisible.

The function is very simple:

JavaScript
function NulA_CMS_switch_on_off(elementid) {
  div = document.getElementById(elementid);
  if (div.style.display == "none") 
     div.style.display = "";
  else
     div.style.display = "none";
  return false;
}

For each html tag the visitor can use I created a button. These buttons are grouped and aligned with divs. I will skip this part. You can see it on my website.

Each button has coding that looks like this:

<input type="image" src="http://www.yourdomain.com/buttons/p.gif" alt="p" title="p"

onclick="javascript:return NulA_CMS_insert('FormName', 'element_name', 'p', 5000, 500)" />

This displays a button with a P on it. ( From <p>, the paragraph-tag.)

The purpose of this button is to put inside the textarea the string <p>your text</p>

When clicked the function NulA_CMS_insert is called with the name of the form, the name of the textarea inputfield the tag, the maximum text-length and the integer critical.

(For critical I use maximum text-length divided by 10. When the textarea is filled for 90%, the visitor gets a warning. See below.)

In this example the tag is <p>.

NulA_CMS_insert() will put the string <p>your text</p> in the textarea at the caret-position with 'your text' selected. The user can simply type and the typed text will be between <p> and </p>.

If you are using Firefox this works fine. With Internet Explorer it does not. I did not try it in other browsers. Maybe later. But feel free to expand the code for other browsers.

The function is very simple. The variable selname is optional and is used for css selectors. It's use will be made clear later in this article.

In the following text I deleted most part of the function. The complete function is in the source-code. The part that is left out handles other tags.

JavaScript
function NulA_CMS_insert(formname, fname, ac, maxlength, critical, selname)
{
  obj = document.forms[formname].elements.namedItem(fname);
  if (obj == null) return false;
  if(typeof(selname) === "undefined") selname = "";
  i_select = 0;
  insert = "";
  switch (ac) {
  case "p":
    insert = "<" + ac + selname + ">your text</" + ac + ">\n";
          i_select = 9; // 'your text' has length 9. we select this text if possible 
          pluspos = 2 + ac.length + selname.length; // the length of the tag plus two for the char '<' and the char '>'
      break;
  }
  pos = get_CaretPosition(obj); // find the current position of the carret
  oldValue = obj.value;
  len = oldValue.length;
  switch (pos) { // insert the string in the textare.value on the position of the caret
    case -1:
    case len:
      pos = len;
      newValue = oldValue + insert;
      break;
    case 0:
      newValue = insert + oldValue;
      break;
   default:
      newValue = oldValue.substring(0, pos) + insert + oldValue.substring(pos, len);
      break;
  }
  obj.value = newValue;
  NulA_CharCount(formname, fname, maxlength, critical); // calculate remaining characters
  if (obj.selectionStart) {
    obj.focus();
   // we inserted <p>your text</p>
   //  now we select the string 'your text'
    obj.setSelectionRange(pos + pluspos, pos + pluspos + i_select);
  } else {
    obj.focus();
  }
  return false;
}

Now the html-tag is inserted and (if the browser allows it) we have selected the string between the start-tag and the end-tag. So the user can start typing his/her own text. (Note: In IE the string is added at the end of the textarea. In Firefox it works as intended. I didn't try other browsers yet.)

Content

Javascript for managing html-input in a textarea

html buttons for a textarea to insert a simple tag

html button for a textarea to insert a tag with css class or css id

The textarea with remaining chars

html button for a textarea to insert a tag with css class or css id

With a webpage you often have css-files. These files have selectors: tags with classes and tags with id's. It is nice when people can use these css-selectors. To enable this I put a submit-button and a select inputfield above the textarea with code like this:

Submit-button with the label '+':

<input class="submit" type="submit" value="+" onclick="javascript:return NulA_CMS_insert_sel('FormName', 'h7', 5000, 500)" />

Note: h7 is the name of the textarea element. You can choose any name for the textarea, but you have to be consistent with the naming.

Select inputfield (with only one option in this case):

<select class="select" id="sb_h7" name="sb_h7" size="1" >

<option selected value="div.comment" style="background-color:#99FFFF;">div.comment</option>

Note: h7 is the name of the textarea element. sb_h7 stands for selectbox for textarea h7.

First you select one of the options. Then you click the button with the label '+'. As a result a string like:

<div.comment>your text</div> is inserted in the textarea at the position of the caret. If you choose another option, you get another css-selector in place of 'div.comment'.

The submit-button has the event:

onclick="javascript:return NulA_CMS_insert_sel('FormCMS', 'h7', 5000, 500). This calls the function:

JavaScript
function NulA_CMS_insert_sel(formname, fname, maxlength, critical)
{
  objSB = document.forms[formname].elements.namedItem("sb_" + fname); // find the selectbox element with css selectors
  if (objSB == null) return false;
  var seloption = objSB.options[objSB.selectedIndex].value; // find the selected item
  var selector = "";
  var elem = "";
  var elname = "";
  for (i=0; i<seloption.length; i++) // find the . or # sign to find out if the selector is a class or an id.
  {
    switch (seloption.substring(i, i+1))
    {
      case ".":
        selector = "class";
        break;
      case "#":
        selector = "id";
        break;
      default:
        if (selector == "")
          elem = elem + seloption.substring(i, i+1); // add the char tot the part that comes before the '.' or the '#'
        else
          elname = elname + seloption.substring(i, i+1); // add the char tot the part that comes after the '.' or the '#'
        break;
    }
  }
// with <option selected value="div.comment"> we get:
// elem = 'div'
// selector = 'class'
// elname = 'comment'
// now we call the function we described above, this time with selname
  NulA_CMS_insert(formname, fname, elem, maxlength, critical, " " + selector + "=\"" + elname + "\"");
  return false;
}

Content

Javascript for managing html-input in a textarea

html buttons for a textarea to insert a simple tag

html button for a textarea to insert a tag with css class or css id

The textarea with remaining chars

The textarea with remaining chars:

After the preparation above we put the textarea on the webpage with

<div id="error_div_h7" style="display:none;color=#FF0000;"><h2>**** ERROR ****</h2></div>

<p class="textcount">Resterend aantal tekens: <b id="b_h7" class="ta_unchanged">5000</b></p>

<textarea class="textarea" name="h7" id="h7" cols="75" rows="10"

onkeydown="NulA_OnKeyDown(event, 'FormCMS', 'h7')"

onkeyup="NulA_CharCount('formname', 'h7', 5000, 4500)" >

</textarea>

First we put an error message above the textarea with style="display:none;" This means that it is not shown. When the visitor types more chars than allowed, we make it visible.

Second we give a message to the visitor with the amount of characters he/she can type in the textarea. Initially this element is given the class ta_unchanged which means textarea unchanged.

The amount of characters that the visitor has left to type is displayed within a bold-tag. When nothing is changed, this tag has the class ta_unchanged. When changed, it gets the class ta_changed. When the visitor has almost used all the characters, it gets the class ta_critical. When the visitor typed to much, it gets the class ta_error. These classes give a different color to the bold text with the remaining characters.

Third we define the textarea with

  • an onkeydown event to handle special keys.
  • an onkeyup event to count the characters after input.

OnKeyDown event:

I use Alt + u for update of a form. When you have a big form with many input fields, you appreciate it if you don't have to scroll down.

I use Alt + a for adding a css-selector as described above. Alt + a does the same thing as pressing the submit-button with the label '+'.

The onkeydown event calls the function:

JavaScript
function NulA_OnKeyDown(event, formname, fname) {
  if(typeof(fname) === "undefined") fname = "";
  if ( event.altKey == true ) { // do nothing if the alt key was not pressed
  if (event.keyCode == 85 || event.keyCode == 117) // submit on alt+u or alt+U
    NulA_submit_function(formname);
  else {
    if (fname != "" && (event.keyCode == 65 || event.keyCode == 97)) { // add the  on alt+a or alt+A
    if (typeof NulA_CMS_insert_sel == "function")
      NulA_CMS_insert_sel(formname, fname);
    }
  }
  }
}

OnKeyUp event:

This calls the function:

JavaScript
function NulA_CharCount(formname, fldname, maxlength, critical)
{
  var objTA = document.forms[formname].elements.namedItem(fldname); // textarea as object
  if (objTA == null)
    return false;
  var objError = document.getElementById('error_div_' + formname + '_' + fldname); // error div as object
  var objBold = document.getElementById('b_' + formname + '_' + fldname); // bold as object
  var remaining = maxlength - objTA.value.length; // chars left to type
  var labelclass = 'ta_changed'; // set the labelclass to a default value.
  if (remaining < 0) { // input is to big. Set the error element to visbible.
    labelclass = 'ta_error';
    if (objError != null)
      objError.style.display = "";
  } else {
    if (objError != null)
      objError.style.display = "none"; // make error element invisble
    if (remaining < critical)
      labelclass = 'ta_critical'; // not many chars left to type
  }
  if (objBold != null) {
    objBold.innerHTML = remaining; // display amount of chars left to type
    objBold.className = labelclass; // set the style (color, font) of the element with the chars left to type
  }
  return false;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy Vote 5 Pin
Shemeemsha (ഷെമീംഷ)28-Oct-14 23:46
Shemeemsha (ഷെമീംഷ)28-Oct-14 23:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.