I need to have a textarea where i can write something. A button. Then another textarea for the answer to appear. For example if someone writes "Hello", they press the button and "Bonjour" appears in the other text area. But without the first textarea and submit button disappearing.
<!DOCTYPE html><html><body><textarea id="test" cols="20" name="S1" rows="2"></textarea><button onclick="myFunction()">Submit</button><script type="text/javascript">
function myFunction() {
var x = "";
if (document.getElementById("test").innerHTML = "Hello") {
document.write("<p>Bonjour</p>");
}
else {
document.write("<p>Nothing Entered</p>");
}
}
</script><textarea id="answer" cols="20" name="S2" rows="2"></textarea></body></html>
but when i input "Hello", instead of the whole thing appearing and "Bonjour", appearing. i want "Bonjour" to appear in the other textarea. I also still want to functionality to still be there multiple times.
On a good day, all of these form elements would actually reside in a <form></form> block, so I added the "return false;" in case you ever implement this in a real form with an 'action' attribute. And I moved the <script> out of the <body> where you should usually insert such code unless it needs to be executed when the page is rendered.
this does not full work, if I just press the submit without typing anything into the boxes both "Bonjour" and "Hello" appears in their respective textareas.
Obviously, your test line assign the value "Hello" to the "text" textarea. This non zero value is true and the value "Bonjour" is assigned to the second textarea !
Change the = sign with a == to compare the two value like this.
<!DOCTYPE html><html><head><script type="text/javascript">
function myFunction() {
var x = "";
if (document.getElementById("test").innerHTML == "Hello"){
document.getElementById("answer").innerHTML = "Bonjour";
}
else {
document.getElementById("answer").innerHTML = "Nothing Entered";
}
}
</script></head><body><textarea id="test" cols="20" name="test" rows="2"></textarea><button onclick="return myFunction();">Submit</button><textarea id="answer" cols="20" name="answer" rows="2"></textarea></body></html>
But when i press submit with "Hello" entered, the output is "Nothing Entered". Also i need this to work multiple times without refreshing the page. e.g. press submit without anything entered, "Nothing Entered" appears, then i type in "Hello", and press submit "Bonjour" appears in the other textarea. Thanks
You have probably to take care with spaces, tabs or carriage returns in the textarea ! Then it could be better to remove all this characters before to make the test with something like this.
Code:
var x =document.getElementById("test").value;
y = x.replace(/(^\s|\s$)/g,'');
if (y == "Hello") {
// do something
}
else {
// do other thing
}
Bookmarks