Reputation: 41
I am completely new to HTML and Javascript. I am using a very simple code to append some text typed in an input field to the text in a textarea. The user should be able to append the text by clicking on the enter button or by just pressing the enter key. I used the code that has been given in this thread and it works fine but as soon as the text gets appended the entire text in the textarea disappears! This only happens when the enter key is pressed. The code works fine when the button is pressed. I think it might be because I am enclosing the textarea and the input in a form tag because when I remove it, it seems to work fine. But I need to send the string typed in the input field to the server as well as display it in the text area. Kind of like a chat app. So can I remove the form field? Also I am not very familiar with how the event object and window.event work. I would really appreciate any kind of help I can get on this. I used the following like as reference.
attempting to make enter button 'clickable'
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form name="frm">
<textarea id="textbox" name="textbox" rows="20" cols="70" readonly>
</textarea>
<input id="prmpt" type="text" name="prmpt" onkeypress="KeyPress(event)"/>
<input type="button" id="enterInst" value="Enter" onclick="doSomething();"/>
</form>
</body>
<script>
function KeyPress(e) {
e = e || window.event;
var key = e.keyCode ? e.keyCode : e.which;
if (key == 13) {
doSomething();
}
return;
}
function doSomething(){
var instruct = document.getElementById("prmpt").value;
if(instruct === "\n")
{
document.getElementById("textbox").value += ">>"+instruct;
document.getElementById("prmpt").value="";
document.getElementById("prmpt").focus();
return;
}
else{
document.getElementById("textbox").value += "\n"+">>"+instruct;
document.getElementById("prmpt").value="";
document.getElementById("prmpt").focus();
return;
}
}
</script>
</html>
Upvotes: 0
Views: 2903
Reputation: 3583
Yes, you are right, this happens because of the <form>
.
Your form is being submitted when you press enter in the input box.
To avoid this, you may add e.preventDefault();
after handling enter key in your KeyPress()
function. Like this:
function KeyPress(e) {
e = e || window.event;
var key = e.keyCode ? e.keyCode : e.which;
if (key == 13) {
e.preventDefault();
doSomething();
}
}
Upvotes: 3