Set textarea value with javascript

How to set the value of a form element using Javascript

As we have seen in earlier articles, in order to work with forms in JavaScript, it is imperative to obtain references to the form object and its elements. In this article, we will be using the forms collection of the document object and the elements collection of the form object to set the values of the form elements. The syntax for accessing the form object is as below:

oFormObject = document.forms['myform_id']; 

For accessing individual elements, we use the following code:

oformElement = oFormObject.elements[index]; 
oFormElement = oFormObject.elements["element_name"]; 

In the above code, “index” refers to the position of the element in the “elements” collection array, and “element_name” is the name of the element. Both approaches give us a reference to the desired form element.

Setting the value of a textarea element using JavaScript

In order to set the value of a textarea field element in a form, we can use the following code:

oFormObject.elements["element_name"].value = 'Some Value'; 

If we are accessing the form object through any of the form’s elements itself, we can also use the following code:

this.form.elements["element_name"].value = 'Some Value'; 

Let us look at a simple form example.

 form id="register_complaint" action="#">  Full Name: input type="text" size="30" maxlength="155" name="name" />  Email Id: input type="text" size="30" maxlength="155" name="email" />  Service Complaint: textarea name="service_complaint" rows="7" cols="50">textarea>  input type="button" name="submit" value="Submit Complaint" onclick="showElements(this.form);" />  form> 

When the page loads, the textarea field “service_complaint” has a note written for the user: “Please enter your complaint briefly”, but when focus is set to that field, this message disappears, as it should. In order to implement this feature, we would need to write an onLoad event handler for the tag that would set the initial value of the textarea element:

 body onload="initForm(document.forms[0], 'service_complaint', 'Please enter your complaint in brief');"> 

The initForm function could be implemented this way:

 function initForm(oForm, element_name, init_txt)   frmElement = oForm.elements[element_name];  frmElement.value = init_txt; > 

You must have also noticed that this initial message does not re-appear even after the focus is removed and again given to this field. We do this by writing an onFocus event handler for the textarea element. The code below is generic, that can be used for other fields like the text input field as well:

 function clearFieldFirstTime(element)   if(element.counter==undefined)    element.counter = 1;  >  else    element.counter++;  >   if (element.counter == 1)    element.value = '';  > > 

The first time the textarea element is given focus, the property “counter” for the textarea element is not defined, and so we can set the counter, by giving it the initial value 1. Thereafter, on subsequent focus, this counter increments. The value of the textarea is reset only the first time the textarea field gets focus, by setting its value attribute to the empty string.

Setting the value of the text input element through JavaScript

In order to set the value of a text input field element in a form, we can use the following code:

oFormObject.elements["element_name"].value = 'Some Value'; 

Let us look at an example to illustrate how to set the value of the text input element through javascript.

The form in this demo has a “membership_period” text input field that is updated through the use of two JavaScript button elements. Have a look at the way the HTML is coded:

 form id="register_complaint" action="#">  Full Name: input type="text" size="30" maxlength="155" name="name" />  Email Id: input type="text" size="30" maxlength="155" name="email" />  Service Complaint: textarea name="service_complaint" rows="7" cols="50">textarea>  Months as member: input type="text" size="5" maxlength="5" name="membership_period" />  input type="button" name="increase" value="+" onclick="monthModify(this.form.elements["membership_period"], 'incr');" />  input type="button" name="decrease" value="-" onclick="monthModify(this.form.elements["membership_period"], 'decr');" />  input type="button" name="submit" value="Submit Complaint" onclick="showElements(this.form);" />  form> 

As you must have seen in the demo, the text field named “membership_period” has a default value of 6 when the form loads, which can be changed either by directly entering the value in the text input field, or by adjusting the value through the two javascript buttons labeled “+” or “-” . We now need to write a javascript function that can serve as the onClick event handler of the two buttons:

In the function, we would first need to identify which of the two buttons was clicked:

 switch(btnElement.name)  case 'increase':  // code to handle incrementing the value of the  // text input field referenced by txtElement  case 'decrease':  // code to handle decrementing the value of the  // text input field referenced by txtElement  > 

For the case ‘increase’, we would need to check if the value we are trying to increment is an integer, and if it is, then we increment it:

 case 'increase':  if(isEmpty(txtElement.value))    txtElement.value = '1';  >  else if(isInteger(txtElement.value))    txtElement.value ++;  >  else    alert('The value you are trying to increment is not a number');  txtElement.value = '';  >  break; 

The function isEmpty() checks whether the value of the text input field is empty or not, and the function isInteger() checks if the value is an integer. If all these tests return true, we increment the value using the construct: txtElement.value ++. Have a look at the code sample for the implementation of these functions.

For the case ‘decrease’ the code is very similar; have a look at the code sample.

See Also

Источник

Set or update value of textarea with JavaScript/jQuery

This post will discuss how to set or update the value of textarea in JavaScript and jQuery.

1. Using JavaScript

With plain JavaScript, you can use either innerHTML , innerText or textContent to write text inside a textarea.

JS

HTML

The innerText property will escape the specified text so that it will render correctly in HTML.
The innerHTML property won’t escape the text, which can lead to XSS attacks.
The textContent property offers better performance since its value is not parsed as HTML, and it also prevents XSS attacks.

2. Using jQuery

With jQuery, you can use the .text() method to replace the textarea’s text.

JS

HTML

Alternatively, you can use jQuery’s .html() method, which uses the browser’s innerHTML property to replace textarea content with the new content completely.

Another good solution is to use the .val() method to set the text value of the textarea element.

JS

HTML

To insert text at the end of a textarea, you can use the .append() method:

JS

HTML

That’s all about setting or updating the value of textarea in JavaScript and jQuery.

Average rating 4.52 /5. Vote count: 31

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂

This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it

Источник

How to Set Text area Value in JavaScript

While creating a web page or the website via JavaScript, there can be a situation where you want to set a specific text value in order to display some specific text or notification message for a specific time interval and then reset it. For instance, displaying the correct answer in response to the provided question especially in the case of filling a form or a questionnaire. In such cases, setting text area value in JavaScript is very helpful in assisting the end-user effectively.This article will focus on the approaches that can be utilized to set textarea value in JavaScript.

How to Set Textarea Value in JavaScript?

To set text area value in JavaScript, the following properties can be utilized:

The stated properties will now be explained one by one!

Approach 1: Set Textarea Value in JavaScript Using the textContent Property

This approach can be implemented to fetch the allocated text and set it accordingly.

The following example illustrates the stated concept.

Example

Firstly, specify the “id” and “name” corresponding to the following text within the “ ” tag:

Next, create a button and attach an “onclick” event invoking the specified function:

After that, declare a function named “settextValue()”. In its definition, get the “id” of the text specified before. Finally, apply the “textContent” property and set the text value assigned before to the below-updated one:

document. getElementById ( ‘text’ ) . textContent = «This is JavaScript»

Approach 2: Set Textarea Value in JavaScript Using the value Property

In this particular approach, the text area value can be set by fetching the specified value and assigning it a newly initialized value.

Example

In the following example, similarly include the following value within the text area having the specified “id”:

Likewise, create the following button having an “onclick” event redirecting to the function setTextValue():

Now, define the function named “settextValue()”. Here, access the id of the specified text. In the next step, assign a new text value to the variable named “valueUpdate”.

Lastly, apply the “value” property upon the fetched text area value and assign it the new value as follows:

var textUpdate = document. getElementById ( ‘text’ ) ;

var valueUpdate = ‘Linuxhint’ ;

textUpdate. value = valueUpdate ;

We have concluded the convenient approaches to set text area value in JavaScript.

Conclusion

The “textContent” property or the “value“ property can be applied to set the text area value in JavaScript. The former approach accesses the specified text area value and sets it abruptly. The latter approach, on the other hand, initializes a new text value and assigns it to the fetched text area value. We recommend you implement the first approach which includes overall less code complexity and is easy to implement as well. This article compiled the approaches that can be helpful to set the text area value in JavaScript.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.

Источник

Читайте также:  To convert a string to an integer in JavaScript
Оцените статью