How would I change the content of a <textarea> element with JavaScript?
I want to make it empty.
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.
If you can use jQuery, and I highly recommend you do, you would simply do
$('#myTextArea').val('');
Otherwise, it is browser dependent. Assuming you have
var myTextArea = document.getElementById('myTextArea');
In most browsers you do
myTextArea.innerHTML = '';
But in Firefox, you do
myTextArea.innerText = '';
Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)
Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.
Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.
Although many correct answers have already been given, the classical (read non-DOM) approach would be like this:
document.forms['yourform']['yourtextarea'].value = 'yourvalue';
where in the HTML your textarea is nested somewhere in a form like this:
<form name="yourform">
<textarea name="yourtextarea" rows="10" cols="60"></textarea>
</form>
And as it happens, that would work with Netscape Navigator 4 and Internet Explorer 3 too. And, not unimportant, Internet Explorer on mobile devices.
If it's jQuery...
$("#myText").val('');
or
document.getElementById('myText').value = '';
Reference: Text Area Object
Put the textarea to a form, naming them, and just use the DOM objects easily, like this:
<body onload="form1.box.value = 'Welcome!'">
<form name="form1">
<textarea name="box"></textarea>
</form>
</body>
Here is a simple vanilla JS example that changes the textarea content on a button click.
const button = document.querySelector("#button");
const messageBox = document.querySelector("#message");
button.addEventListener("click", ()=>{
messageBox.innerText = "Please type your message here."
});
<h1>TextArea Examplw with JavaScript</h1>
<textarea id="message"></textarea>
<button id="button">Click to Change</button>
Related
I would like to make a textarea and a div near it similar to what you use in the "ask question" page here in stackoverflow.
You type a text in the textarea and the text is rendered live under the textarea.
I'd like to make this to convert "live" some codes like "a024" typed in the textarea to symbols in the div.
Do I need to use javascript to get this feature?
Thanks.
Yes. That was called DHTML for Dynamic HTML at the beginning of JavaScript.
You will have to use Javascript to create this behavior.
You can get the value of an element with something like:
var source = document.getElementById("sourceTextarea").value;
and set text in a destination element with something like:
document.getElementById("destinationDiv").innerText = "some text";
In your HTML you will have to use :
<textarea id="sourceTextarea"></textarea><div id="destinationDiv"></div>
You will definitely need Javascript to achieve this goal.
You can make use of the 'onkeyup' property of the textarea to bind a javascript function the keyup event.
Once you do this, you can process the texarea value to replace whatever you need to.
function updateMyDiv() {
var myTextarea = document.getElementById("myTextarea");
var myDiv = document.getElementById("myDiv");
myDiv.innerHTML = myTextarea.value;
}
<html>
<body>
<textarea id="myTextarea" onkeyup="updateMyDiv()">
</textarea>
<div id="myDiv">
</div>
</body>
</html>
Its probably something basic but wanted explanation of the use cases. Like sometimes hitting "enter" inputs the data, while sometimes mouseclicks work. I'm concerned about "Gotchas" that I would have overlooked. Like maybe it works in Firefox but not in Chrome for example.
I saw the following 2 ways, both are ways to input data into a form element.
First way
JavaScript
var $body = $(e.target).find('[name=body]'); //defines the content
var comment = { body: $body.val() };
HTML
<form class="form-send-message" id="addcomment" data-keyboard-attach>
<textarea id="body" name="body"></textarea>
</form>
Second way
JavaScript
var message = template.find('input').value;
HTML
<form class="message" data-keyboard-attach>
<input type="text" name="body" id="body">
<button class="icon" type="submit"></button>
</form>
Here you can see two ways to find the value of an input/textarea with an explanation:
'submit .new-post': function(event){
//returns name="postBody" content from the form you're submitting
var postBody = event.target.postBody.value;
//returns the value of an html element that exists in DOM, even if its inside a different template or form.
var postBody = $('.someClass').val()
}
Your first code Is jQuery, while your second code is Meteor. They both can accomplish the same thing under the right circumstances. Also, according to this answer, meteor's template.find is an alias for jQuery's $, meaning they are the exact same.
But, the codes don't do the same thing in this case.
Your first code finds the value an element with a name of "body" inside e.target. I am assuming e is an Event, but there is no way to tell with the current amount of code you gave.
The second code just gets the value of the first INPUT element it finds.
I have created a very simple editor that has been working great. However, I just tried to put JavaScript into it and I can't get it to work.
The code for the editor:
<div id="buttoncontainer">
<input id="button" onclick="update();" type="button" value="Update page">
</div>
<div id="tryitcontainer">
<textarea id="codebox"></textarea>
<iframe id="showpage"></iframe>
</div>
The JavaScript for the editor:
<script>
function update() {
var codeinput = document.getElementById('codebox').value;
window.frames[0].document.body.innerHTML = codeinput;
}
</script>
I just wanted to run some simple JavaScript that changes an image when it is clicked. This code works fine when I run it in a full browser, so I know its the editor thats the problem.
Is there a simple fix for this that I'm missing?
The button is not finding the update() method. You need that function to be globally available:
http://jsfiddle.net/t5swb7w9/1/
UPDATE: I understand now. Internally jQuery basically evals script tags. There's too much going on to be worth replicating yourself... either use a library to append, or eval the code yourself. Just a warning that eval'ing user input is rarely a good thing and is usually a welcome mat for hackers.
window.myScope = {
update: function() {
var div = document.createElement('div'),
codeinput = document.getElementById('codebox').value,
scriptcode = "";
div.innerHTML = codeinput;
Array.prototype.slice.apply(div.querySelectorAll("script")).forEach(function(script) {
scriptcode += ";" + script.innerHTML;
div.removeChild(script);
});
window.frames[0].document.body.appendChild(div);
// hackers love to see user input eval'd like this...
eval(scriptcode);
}
};
And then you would update your button like so:
<input id="button" onclick="myScope.update();" type="button" value="Update page">
Or, even better, use addEventListener and forget the onclick part altogether. I'll let you do that research on your own ;)
JavaScript inserted via innerHTML will not be executed due to security reasons:
HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
from MDN: Element.innerHTML - Security considerations, see also: W3: The applied innerHTML algorithm.
A possible solution using the jQuery method .append() works around that, as it somehow evals the content. But this will still not solve your problem, as the JavaScript code is executed in the current scope.
Here's a test scenario:
function update() {
var codeinput = document.getElementById('codebox').value;
$(window.frames[0].document.body).append(codeinput);
}
Try it here
Try to insert this script:
<script>
alert( document.getElementById('tryitcontainer') );
</script>
and this one:
<p id="test">Test</p>
<script>
window.frames[0].document.getElementById('test').innerHTML = 'updated';
</script>
The first one will return a [object HTMLDivElement] or similar. Here you can see, that you're still in the same scope as the parent frame. The second one will correctly update the content within the iframe. Keep that in mind, when experimenting with those things.
Maybe Executing elements inserted with .innerHTML has some more infos for you.
The following var is only working in my script when the text is hard coded in the textarea (e.g. London):
script
var thought = $('textarea[name=search]').val(); //...used in object literal
html
<textarea rows="5" name="search" type="text" id="term">London</textarea>
I'd like to be able to type a search term into the textarea and search for it but it's not working?
I've tried all of the answers below with no luck!? I've therefore included the following in the object literal. It pulls the hard coded value from the textarea (like before) but it doesn't pull a value that is typed in the textarea normally? I thought this might be easier to resolve the problem (the feed not working when the search term is typed in)
search: $('textarea[name=search]').val(),
I'm following this tutorial below for a twitter feed with jquery but adding a textarea to search for terms,topics,hashtags etc is proving difficult to figure out.
Twitter Feed with Jquery linky
Do with keyup or change event of textarea
$("textarea[name='search']").keyup(function(e){
var currentText=this.value;
});
You have a couple options, either search using a click event on some button called Search, or use a change / keyup event to grab the new value each time the field is updated, and perform the search that way:
$("#term").keyup(function() {
console.log(this.value); //theres your value!
});
As stated before, if you use it like this, it will be stored in the thought var and you can call it from whatever function you're using.
Since your method calls it one time probably before you edit it.
At least that is what I'm guessing since your code is obviously not complete ;).
var thought = '';
$('textarea[name=search]').keyUp(function(){
thought = $(this).val();
});
Just add jquery and use below code.
<html>
<head>
//import jquery here
<script>
$(document)
.on("click", "#btn", function(event) {
var thought = $('textarea[name=search]').val();
alert(thought);
});
</script>
</head>
<body>
<textarea rows="5" name="search" type="text" id="term"></textarea>
<input type="button" id="btn" value="click me">
</body>
I have a function that deletes a textfield (called termsField) and uses JQuery to empty the text from a div (called definitionContainer), and I activate the function when the user clicks on a button.
function clearText(target){
var definitionDiv = document.getElementById("definitionContainer");
$('#definitionContainer').empty(); //empty the div
termsField.value = ""; //delete the text field
$(target).val = "";
And this is the HTML for my textfield and button:
<input id="termsField" type="search" autocorrect="off"
placeholder="Type something!" maxlength="2048">
<INPUT type="image" name="Clear" alt="Clear Search" src="clearX.png"
height="22" width="22" onClick="clearText(this)">
Does anyone have any idea why clearing the definitionDiv works in Firefox but termsField.value = ""; doesn't work? Both of these work fine in Safari and Chrome. I'm not bothering with testing IE since this is part of a web interface.
You haven't shown where the variable termsField is defined. Maybe you haven't defined it, which is likely to be the problem, since not all browsers do the hideous thing (introduced by IE) of polluting the global object with properties corresponding to the IDs of elements within the document. The following works fine for me:
var termsField = document.getElementById("termsField");
termsField.value = "";
Also, although this is unrelated to the problem with termsField, jQuery's val() is a method:
$(target).val("");
$(target)[0].value = 'blah';
or
$(target).val('blah')
Also you do not have termsField defined anywhere. Please define it if you already haven't in an outer scope.
right syntax is
document.getElementById('termsField').value = ""
assuming 'termsField' is the id, as you specified above.