JavaScript

Javascript Textarea Example

If you have applied somewhere online, or asked for a particular thing using the contact forms of the websites, you will most probably have seen those use a text-area field for the argumentation. It is a highly convenient feature of Javascript, and if you now want to add it to your own website, I would completely agree. But how can you do this exactly? See below!

1. The <textarea> element

The <textarea> tag represents an HTML element that consists of a text input field with multiple rows. It can hold an unlimited number of characters and usually has Courier set as it’s fixed font. There are two ways to define it’s size, one being by specifying the number of it’s columns and rows and the second can be done through the usage of CSS’ width and height.

This element has a corresponding object in Javascript which is the Textarea Object. It is supported by every browser, and is one of the many who got to be improved a lot with the presenting of HTML5 for everyone, as many other properties and methods were added to it. This element supports all the Global and Event attributes in HTML and implements the HTMLElement interface as every other element, but except from that also implements the HTMLTextAreaElement interface. Let’s see each of these aspect of the <textarea> element separately below.
 

2. <textarea> attributes

We mentioned above that as <textarea> is an element who got to be changed and improved a lot with the usage of HTML5. This happened because a number of new attributes were added to it.

2.1 HTML Attributes

Two of the most basic attributes of the element are cols and rows, both of the integer format, which are used to specify the visible width and length respectively of the input section in regards to an average character size. If specified, they must both be a positive number, else the default value is 20.

The disabled attribute is a boolean value that shows whether or not the user is to interact with the control. By default this attribute is set to 0, or otherwise inherited by the parent element.

The name attribute is used to give a name to the control which can be used later to manipulate it’s information.

Another attribute which has been there since the beginning is readOnly, which is a boolean value that shows whether or not the control should be read-only. The difference between this one and disabled is that it doesn’t prevent the user from selecting text or clicking in the control, while the first one does. However, readOnly does allow to submit the value of the textarea with the form.

defaultValue sets or returns the default value of the control in case it is not completed by the user while form returns a reference to the form that contains the text area. We use value to set or return the contents of the element, and type to get the type of the form element the text area is.

2.2 HTML5 Attributes

Some of the most important attributes that were added with HTML5 are: autocomplete, autofocus, form, maxlength, minlength, placeholder, required, selectionDirection, spellcheck, wrap etc. Let’s see what they do each at a time.

  • autocomplete – shows whether or not the browser should automatically complete the value of the control or not. When set to off the browser does not autocomplete the value, so it’s either explicitly entered by the user or autocompleted by the methods of the document. Otherwise, the browser automatically completes the value based on other values previously entered by the user in the form.
  • autofocus – is a boolean value that allows the control to have input focus when the page loads. Only one of the input fields can have this attribute set to YES in a form.
  • form – returns the ID value of the containing form element. In the cases where the <textarea> element is not a descendant of a form element, it will either return the ID value of the containing element, or null.
  • maxLength – specifies the number of characters to be inserted in the control. Usually, it is specified only when you want it to be a different value from that of the default, otherwise it’s left untouched. There is also a similar attribute named minLength. Can you guess what it does?
  • placeholder – is a string which normally offers the user an idea about what to enter in the control. However, it can be whatever you want it to be, and being funny and creative always pays off *hint-hint*.
  • required – is used to indicate a value which is customary to be filled before submitting the form, which would make it unable to be submitted if it’s left uncompleted.
  • selectionDirection – is an attribute which specifies the direction in which the selection is required to happen. It can either be forward in case the selection happens from the start to finish, or backward in case the selection happens starting from the end and going until the start, or none in case both of these options are allowed and we have no information on the direction.
  • spellcheck – is a boolean value which when set to TRUE shows that the element is to have it’s grammar and spelling checked, and to be left as it is in case it’s set to FALSE. It’s value can be inherited from the parent element of which the <textarea> element is descended.
  • wrap – is an attribute that indicates how the control wraps text. It can have two values: hard and soft. The first one inserts a line break so that each line has no more character than the width of the control, which is also why setting the attribute to this value, you will have to also specify the cols value. The second one, soft, is also the default value for wrap in case it’s left unspecified, and is used to show the browser that it’s to respect any line break pair (CR+LF) but not insert any on it’s own accord.

With that, we have explained the most used and most important attributes regarding the <textarea> element.

3. <textarea> methods

Except for all the attributes that will help us set a <textarea> element just the way we need it to work, there are also a number of Javascript methods related to it which need to be used in order to make it all work. Some of the most important ones are:

  • select() – selects all the contents of the control
  • focus() – similarly to the focus attribute, this method gives input focus to the control
  • blur() – reverses the effect of focus(), which means that it removes input focus to the control. This method and also focus() are inherited from the HTMLElement interface starting from HTML5 and on, but needed to be defined in earlier versions.
  • checkValidity() – this method returns a boolean value as it’s final result. This value would be TRUE in the cases where the control is not a candidate for constraint validation or it’s criteria is fulfilled, and FALSE when these constraints are not fulfilled.
  • setCustomValidity() – would return a custom string (presumably hinting at what’s wrong) in case the validity criteria is not met, and a void string if everything is as it should be.

By now you know a lot about the <textarea> element, including a great number of it’s attributes and methods. However some of you might still have some difficulty understanding this element. The best way to clear your doubts? Why, practice, of course. Time for some examples!

4. Creating a simple <textarea> element

There are two ways to create a very basic textarea: using only Javascript and using the <textarea> tag. Let’s see them both in action below!

4.1 Using Javascript

To create a textarea using strictly plain Javascript we would only need the function which does this and something to trigger it’s execution, which can be either a button being pressed or anything, really. As usual, we will separate the Javascript and HTML parts of our code, even though in our case it’s not strictly necessary. That’s because it’s good programming practice in case you have large chunks of code to deal with!

The heart of it, of course, would be the Javascript code, which we will place in a separate file named textarea.js simply like below, without any tags or anything else. Just the code!

textarea.js

function createOurTextarea() {
    var ourElement = document.createElement("TEXTAREA");
    var ourElementText = document.createTextNode("This is our TextArea!");
    ourElement.appendChild(ourElementText);
    document.body.appendChild(ourElement);
}

It is pretty simple to understand what we’ve done here: We create a textarea element, create a text node for it and append it to the first one, and lastly, append these two both to the document body. All this is wrapped into a function, which we will use to trigger the textarea. We would do that by clicking a button which fires this function as soon as it’s clicked. The HTML code would go like below:

textarea.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Textarea</title>
    <script src="textarea.js" type="text/javascript"></script>
</head>
<body>

<button onclick="createOurTextarea()">Create TextArea</button>

</body>
</html>

There you have it!

4.2 Using the <textarea> tag

I think that all would agree with me in saying that the easiest way to create a textarea element would be through using the tag and some of the attributes for this element according to the needs we have. Of course, later on we can add more functionality to it using Javascript functions, but for now, to create it, we would only need the code snippet below:

textarea.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Textarea</title>
    <script src="textarea.js" type="text/javascript"></script>
</head>
<body>

<textarea name="comments" cols="40" rows="6"></textarea> 

<p><input type=SUBMIT value="submit"></p>

</body>
</html>

As you can see, we only used the tag together with three of the attributes explained above: name, cols and rows. Also, we used a submit button, which we do not strictly need for the textarea, but is usually there to submit the info. However, usually we only have one submit button for all the form.

5. Getting data from the textarea

A common action regarding textareas is getting the data from them and manipulating it. Let’s see how we can get it and then display it for the user. The HTML code would go like below:

textarea.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Textarea</title>
    <script src="textarea.js" type="text/javascript"></script>
</head>
<body>

Data:
<br>
<textarea name="comments" id="myTextarea" cols="40" rows="6">Suppose we have this text!</textarea>

<br>
<button type="button" onclick="getAndDisplay()">Get Textarea Data</button>

<br>
Display Data:
<br>
<p id="display"></p>

</body>
</html>

In the code above we have kept the textarea we created (and discarded the submit button) and added it an id attribute with the value myTextarea. For ease of use, our textarea is not empty.

Then, we have created a button which when clicked invokes the function getAndDisplay(), which we will explain later on. Then we have placed a paragraph with an id of display, both of which will be used in the function.

The Javascript code would go like below:

textarea.js

function getAndDisplay() {
    var x = document.getElementById("myTextarea").value;
    document.getElementById("display").innerHTML = x;
}

As you see, we only have to get the value of our textarea element by using it’s ID, and then pass it to the innerHTML of another element, which we’ve chosen to be the paragraph with the ID value of display. Easy, right?

6. Download the source code

This was an example of Textareas in Javascript.

Download
You can download the full source code of this example here: Textarea

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button