How to Change the Content of a <Textarea> with JavaScript

How to change the Content of a textarea with JavaScript

Like this:

document.getElementById('myTextarea').value = '';

or like this in jQuery:

$('#myTextarea').val('');

Where you have

<textarea id="myTextarea" name="something">This text gets removed</textarea>

For all the downvoters and non-believers:

  • Here's the MSDN reference

    value Property: Retrieves or sets the text in the entry field of the textArea element.

  • Here's the MDN reference

    value DOMString The raw value contained in the control.

Changing value of textarea with JavaScript

The sleep function locks the browser for the period it's "sleeping". If you want to simulate typing, use setTimeout to create a pause between actions that allows the browser to get on with other work:

<script>
function typeIt(msg, el) {
var i = arguments[2] || 0;
el.value = msg.substr(0, ++i);

if (i < msg.length) {
setTimeout(function(){typeIt(msg, el, i)}, 1000);
}
}
</script>

<form>
<input id="i0"><br>
<input id="i1"><br>
<input type="button" value="Type it" onclick="
typeIt(this.form.i0.value, this.form.i1)
">
</form>

There are a number of other approaches using closures and setInterval, however the above is simple and does the job (I think).

Changing the value of a Textarea in javascript

You will need to use setAttribute(), since data-initial-value is an attribute of that tag.

document.querySelector(".KHxj8b").setAttribute("data-initial-value", "The value");

Change "The value" to what ever you want it to be.

How to replace text in textarea element using javascript?

Your problem is likely to have less to do with the browser and more to do with user modifications to the field.

The innerHTML of a textarea is its default value. Use value to get and modify its current value.

You should almost never touch the innerHTML of a textarea. Use the value property instead.

Is there any way to change value of textarea with HTML

I've solved it, see this post

In other to make the element look like textarea, you should translate a carriage return into a br html tag.


In this post:

You could just apply CSS white-space:pre on the element, exactly like the HTML textarea element is internally doing:

<span style="white-space:pre">your  text  \n will \n be \n on multiple \n lines</span>

Also read this comment - about carriage return

how to update p element as I change the textarea?

Hi use this for the preview and the editor var to get the value

var editor = document.getElementById("editor"); 
var preview = document.getElementById("preview");

editor.addEventListener("change",() => {

this.preview.innerHTML = "";
this.preview.innerHTML = editor.value;});
<textarea id="editor" type="text"></textarea>
<p id="preview"></p>


Related Topics



Leave a reply



Submit