shannonmac
shannonmac

Reputation: 17

Insert the contents of a textbox as paragraph text dynamically with JavaScript

I'm new to JavaScript and I am trying to dynamically add the text from the input box into a paragraph (at the top of the page, under the 2 headlines).

I have a JSFiddle that I am working with here

This is my function:

    function addText() {
            var newParagraph = document.createElement('p');
        newParagraph.textContent = textArea;
        document.getElementById("id1").appendChild(newParagraph);
        myDiv.insertBefore(newParagraph, textArea);
        }

    document.getElementById("textArea").onblur = addText;

However, as you can see, on the onblur, it is doing this: [object HTMLTextAreaElement]

I am not sure where I am going wrong.

Upvotes: 0

Views: 2806

Answers (1)

Walter Macambira
Walter Macambira

Reputation: 2605

You are inserting the textArea as the text inside the newParagraph. As it expects a string, is is converting the textArea into a string representation, which is "[object HTMLTextAreaElement]"

Instead, do this:

newParagraph.textContent = textArea.value;

Then, your code would be:

    function addText() {

        var newParagraph = document.createElement('p');

        newParagraph.textContent = textArea.value;
        document.getElementById("id1").appendChild(newParagraph);
        myDiv.insertBefore(newParagraph, textArea);

    }

    document.getElementById("textArea").onblur = addText;

As you told me you want to prepend the new paragraph, use the following:

     parentObject.insertBefore(newParagraph, parentObject.firstChild);

Hope I helped you out!

Upvotes: 2

Related Questions