Javascript – Write to textarea when enter key is pressed

enterformsjavascriptkeysubmit

I have a textarea, which will handle output, and a textfield which will handle user input.

Focus will be entirely on the input field.
I can't make it so that the user input field will add text when the form is submitted (enter key is pressed). It will only work if there is a button and this is clicked. How do I solve this issue?

Below is the code i'm trying for the enter key submit.

<html>
<head>
<script type="text/javascript">
  function addtxt(input) {
    var obj=document.getElementById(input)
    var txt=document.createTextNode("blah blah")
    obj.appendChild(txt)
  }
</script>
</head>
<body>
<textarea id="textarea1"></textarea>
<br><input type="text" onSubmit="addtxt('textarea1');">
</body>
</html>

Best Answer

This will do the job. Also, you should deal with the value property of the textarea rather than appending text nodes to it: if the user changes the textarea's value at all, changing its child nodes afterwards will have no effect. If you want the textarea to be read-only, add a readonly attribute: <textarea id="textarea1" readonly></textarea>.

<script type="text/javascript">
    function inputKeyDown(evt, input) {
        if (evt.keyCode == 13) {
            var textarea = document.getElementById("textarea1");
            textarea.value += "\n" + input.value;
            input.value = ""; // I'm guessing you may want this
            return false;
        }
    }
</script>

<input type="text" onkeydown="return inputKeyDown(event, this);">