I need to type something inside a textarea, then take the text that was written there and store it in a variable.
Example:
I type "Hello" in a textarea.
I want the variable to be: x = "Hello"
I've tried
document.getElementById("someId").value;
which doesn't work for me
<textarea id="ide" rows="13" cols="60"></textarea>
Seems I didnt explain the question right, I wanted to store the value everytime you type but I found a way:
function val(e) {
console.log(e.value);
}
<textarea id="ide" rows="13" cols="60" onkeyup="val(this);"></textarea>
and this is the answer in case anyone wondered, thanks for the replies!
function val(e) {
var someText = e.value;
console.log(someText )
if (someText == "text") {
document.getElementById("msg").innerHTML="new text";
}
}
var valueInVar = ''; function textareaToVar(){ valueInVar = document.getElementById("myTextarea").value; alert(valueInVar); }
<textarea id="myTextarea" onfocusout="textareaToVar()"></textarea>
<!DOCTYPE html>
<html>
<body>
Address:<br>
<textarea id="ide" rows="13" cols="60">Hello</textarea>
<p>Click the button to change the contents of the text area.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("ide").value;
alert(x);
}
</script>
</body>
</html>
Your ID is different it is "someid" in your javascript and "ide" in your HTML. You need to change your code to:
<textarea id="ide" rows="13" cols="60"></textarea>
document.getElementById("ide").value;
You also need to make sure your DOM is loaded before trying to get the value.
<script type="text/javascript">
window.onload = function() {
document.getElementById("delete").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
alert('Alert message here');
}
};
</script>
You need to tell your program when you want the contents of textarea to be put into a variable.
For example, if you want it to happen every time you type something you need to add an 'input' event listener to the textarea:
let text; let textarea = document.getElementById('ide'); textarea.addEventListener('input', function getText() { text = textarea.value; });
If you want to get the value when a button is clicked, then add click event to that button.
let text; let textarea = document.getElementById('ide'); let button = document.getElementById("btn"); button.addEventListener('click', function getText() { text = textarea.value; });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.