gilbert-v
gilbert-v

Reputation: 1305

<input> value lost on keyup / .innerHTML call

I'm working on a project which imitates a console window. When the user presses enter, a new <input> text field is added to the screen and focused upon. The only problem is that the values of the previous <input> fields are lost in the process.

Here is my code:

<!DOCTYPE html>
<html>
    <head>
        <link rel='stylesheet' href='style.css'/>
        <script src='script.js'></script>
    </head>
    <body>
        <input type="text" class="console_window"/>
    </body>
</html>

var input;

function init() {

    function keyup(e) {
        switch(e.which) {
            case 13:
                document.body.innerHTML += 
                    "<input type='text' class='console_window'/>"  

                input = document.getElementsByClassName("console_window")[document.getElementsByClassName("console_window").length-1]; 

                input.focus();

                break;
        }
    }

    document.addEventListener("keyup", keyup, false);
}

document.addEventListener("DOMContentLoaded", init, false);

And the Fiddle.
Also, I prefer not to use plugins.

Thanks!

Upvotes: 1

Views: 1280

Answers (3)

Ben Temple-Heald
Ben Temple-Heald

Reputation: 708

http://jsfiddle.net/894yo3ja/

var input;

function keyup(e) {
    switch (e.which) {
        case 13:
            var i = document.getElementsByClassName("console_window").length + 1;
            document.getElementById(i - 1).setAttribute("value", document.getElementById(i - 1).value);
            document.body.innerHTML += "<input type='text' class='console_window' id='" + i + "'/>";
            document.getElementById(i).focus();
            break;
    }
}

document.addEventListener("keyup", keyup, false);

Hope that helps, the value doesn't get stored, so you have to set the value attribute.

The issue you have is that when you re write the inner html out, the value that you have entered into the input is wiped out. To actually set the value to the input before overwriting the inner html on the body you would need to call .setAttribute("value",value); on the input.

Upvotes: 2

LcSalazar
LcSalazar

Reputation: 16841

It's because your are reseting the page's html markup...

Instead of addind pure HTML text, you should consider using DOM elements manipulation:

Updated Fiddle

var inp = document.createElement("input");
inp.className = "console_window";
inp.type = "text";

document.body.appendChild(inp);
inp.focus();

Upvotes: 7

Brennan
Brennan

Reputation: 5742

When you do document.body.innerHTML += "<input type='text' class='console_window'/>", you are destroying all the input elements and recreating them. When you do this, the values do not copy over. You want to use something like appendChild to add the new input element to the DOM.

Upvotes: 3

Related Questions