I create a textarea and then I want, with Javascript or what I need, to fill the textarea with a content of a file, when I clicked a button.
How can I do that, or what do I need?
I create a textarea and then I want, with Javascript or what I need, to fill the textarea with a content of a file, when I clicked a button.
How can I do that, or what do I need?
Is the text already loaded into the page and held in a Javascript variable? If not, as other have suggested then an AJAX call may be required to retrieve this data.
Changing the value of a textarea can be done with some simple javascript as below;
<textarea id="textarea"></textarea>
<input type="button" onclick="changeText()" value="button" />
<script>
function changeText() {
var textarea = document.getElementById('textarea');
textarea.value = "new Value";
}
</script>
If instead we're retrieving a file without jQuery the function can be as below;
function changeText() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'request_page.php');
xhr.send(null);
xhr.onreadystatechange = function () {
var status = 4;
var http_code = 200;
if (xhr.readyState === status) {
if (xhr.status === http_code) {
var textarea = document.getElementById('textarea');
textarea.value = xhr.responseText;
} else {
// do something with an error here
}
}
}
};
Sounds like a job for an ajax call. Javascript can call a page on the server that can open a file, read its contents and return in a json string containing the contents of the file, which the javascript then puts into the textarea
Load text from local .txt file into html textarea using JavaScript