1

I'm finally getting around to learning Javascript; I am trying to do something simple: capture keyboard input while providing output. I get semi-responsive output for keyboard presses, however I am not able to append the output portion of the page with a line of input once enter is pressed. What am I doing wrong?

<script language="javascript">
    processCommand = function(cmd) {
        if (this.text == null) this.text = "";
        this.text = this.text + cmd + "<br>";
        document.getElementById("outputID") = this.text;
    }
    document.onkeydown = function(evt) {
        if (this.text == null) this.text = ""; 
        var keyChar = String.fromCharCode(evt.keyCode);
        this.text = this.text + keyChar;
        if (evt.keyCode == 13) {
            processCommand(this.text);
            this.text = "";
        }
        document.getElementById("input").innerHTML = this.text;
    };
</script>
<spad id="outputID"/><br>
<hr>
<spad id="input"/>
2
  • 1
    It's document.getElementById("outputID").innerHTML = this.text not document.getElementById("outputID") = this.text;. Commented Oct 24, 2015 at 4:16
  • 1
    First thing I would do is introduce a variable for document.getElementById("outputID") and document.getElementById("input") elements. No need to look them up on every key press Commented Oct 24, 2015 at 4:17

1 Answer 1

3

http://codepen.io/anon/pen/gavNOm

<script language="javascript">
 processCommand = function(cmd) {
    if (this.text == null) this.text = "";
    this.text = this.text + cmd + "<br>";
    outputID.innerHTML = this.text;
}
document.onkeydown = function(evt) {
    if (this.text == null) this.text = ""; 
    var keyChar = String.fromCharCode(evt.keyCode);
    this.text = this.text + keyChar;
    if (evt.keyCode == 13) {
        processCommand(this.text);
        this.text = "";
    }
    input.innerHTML = this.text;
   };
 </script>
 <span id="outputID"/><br>
<hr>
<span id="input"/>

The id's are attached to the window object, by the way using vars in functions is much less confusing.

Sign up to request clarification or add additional context in comments.

2 Comments

this.text in both functions are intended to be two separate variables
ok thanks for the tips. now I need to discover why processCommand seems to work only once

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.