user68760
user68760

Reputation: 3

My function won't add a paragraph to the document

I'm trying to make a button add a paragraph from a text input

http://jsfiddle.net/3gf7tqvo/

JavaScript:

function addParagraph() {
    var textinput = document.getElementById("pageinput");
    var newParagraph = document.createElement("p");
    newParagraph.textContent = textinput;
    document.getElementById("updateDiv").appendChild(newParagraph);
}

document.getElementById('a').onClick = addParagraph;

HTML:

<button id='a'>Click Me!</button>
<input type="text" id="pageinput">
<div id='updateDiv'></div>

ฺBut after an hour of frustration, I can't see why it just won't add the paragraph.

Upvotes: 0

Views: 37

Answers (2)

Alex Char
Alex Char

Reputation: 33218

You have to take the value of text:

function addParagraph() {
  var textinput = document.getElementById("pageinput");
  var newParagraph = document.createElement("p");
  newParagraph.textContent = textinput.value;//here take the value of input text
  document.getElementById("updateDiv").appendChild(newParagraph);
}

//document.getElementById('a').oncClick = addParagraph; onclick is the corect syntax
<button id='a' onclick="addParagraph(); return false;">Click Me!</button>
<div id='updateDiv'></div>
<input type="text" id="pageinput">

p.s. Always like more to add events in element.

Upvotes: 0

friedi
friedi

Reputation: 4360

You made two little mistakes:

  1. Use textinput.value instead of textinput like so:

    newParagraph.textContent = textinput.value;
    
  2. Write onclick instead of onClick like so:

    document.getElementById('a').onclick = addParagraph;
    

DEMO

Upvotes: 1

Related Questions