DVLanleyC
DVLanleyC

Reputation: 153

Create an UL-list with a text input and button

I want to write some text, click a button and the text added has to make a list.

This is what I have at the moment :

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>3-2</title>
<script type="text/javascript" src="js/oefening3-2.js"> </script>
</head>

<body>
<p> <span> geef een tekst in<input type="text" id="waarde"> <input type="button" value="Voeg toe" onClick="a();"></span></p>
<ol>
<p> <span id="waarden"> waarde </span> </p>
</ol>

And the Javascript code :

function a()
{
var ingevoerd = document.getElementById("waarde").innerHTML;
document.getElementById("waarden").add(ingevoerd);  
}

I can understand it doesnt make much sence but I have not really a clue how to do this. Enter some text, click the button and the text has to be in a not numbered list. Can annyone help me out? Would be much appreciated!

Kind regards!

Upvotes: 1

Views: 3332

Answers (1)

bloodyKnuckles
bloodyKnuckles

Reputation: 12079

HTML:

geef een tekst in<input type="text" id="waarde">
<input type="button" value="Voeg toe" onClick="a()">
<ul id="waarden"></ul>

Javascript code:

function a() {
    var node = document.createElement("LI");
    var textnode = document.createTextNode(document.getElementById("waarde").value);
    node.appendChild(textnode);
    document.getElementById("waarden").appendChild(node);
}

JSFiddle demo: http://jsfiddle.net/BloodyKnuckles/y1fk1q70/


Explanation:

The HTML consists of a few elements:

  • Text
  • Text Input
  • Button
  • Unordered List

The button click handler is instructed to execute function a when clicked.

The Javascript then performs the following steps:

  1. Create a list node element. (Not yet attached to DOM [the page].)
  2. Grab the text value of our Text Input and create a text node element from it. (Also not yet attached to DOM.)
  3. Append Text Node to the List Node.
  4. Append the List Node to the unordered list in the DOM.

Upvotes: 4

Related Questions