-1
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <center>
        <input type="text" id="item" onkeydown="if (event.keyCode == 13) document.getElementById('getItem').click()">
            <button id="getItem" onclick="getItem()">Add to List</button>
            <button onclick="getClearItem()">Clear</button> <hr color="gray" id="lineDivider">
            <button onclick="getClearList()">Clear List</button> <br>
        <textarea readonly id="list"></textarea>
    </center>

</body>

<script>
    function getItem() {
        if (document.getElementById("list").value == "") {
            document.getElementById("list").value += document.getElementById("item").value;
    }
        else { 
            document.getElementById("list").value += \n document.getElementById("item").value;
        }
}

    function getClearItem() {
        document.getElementById("item").value = ""
    }

    function getClearList() {
        document.getElementById("list").value = ""
    }
</script>

</html>

This is what I am trying to do:

You enter some text into the "item" textbox and click the "Add to list" button. Then if the "List" textarea is blank it adds the text without inserting a line break. But if there is already some text in the textarea, it inserts a linebreak and then adds the text. I am not sure what I am doing wrong, or how it should even be done.

When I remove the if else statement and just use document.getElementById("list").value += document.getElementById("item").value; it works. When I add the \n to that, it does not add anything to the blank field.

I apologize if my question is unclear.

3
  • 1
    You really should learn to look at the error or debug console in the browser to see when you have script errors. Those script errors will immediately tell you when you have an error like this that is aborting your script and it will usually tell you what line the error is one and sometimes tell you what the error is. Commented Apr 6, 2015 at 18:03
  • 1
    I was waiting for this question based on your earlier question. :) And you did not copy the answer from that post correctly it seems. Commented Apr 6, 2015 at 18:13
  • Haha sorry guys, I'm new to JS entirely so I didn't realize it was just a stupid syntaax error. I'll remember the debugger from now on :D thanks! Commented Apr 7, 2015 at 19:17

1 Answer 1

5

You have to quote the newlines, as in "\n"

document.getElementById("list").value += "\n" + document.getElementById("item").value;

FIDDLE

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

Comments

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.