Search code examples
javascripthtmlfunctionappendchildcreateelement

HTML how to add an input tag to an ordered list using a javascript function


I am trying to add blank input fields to an ordered list (with id = myList) when the user clicks a button. I have written the following code to add a list element to the ordered list, then insert an input field in that new list element. When I execute this code, nothing happens when I hit the button.

Any ideas as to what I'm doing wrong?

  <script type="text/javascript">
     function addToList()
     {
        var doc = document.getElementById("myList");
        var newLI = document.createElement("li");
        var input = document.createElement("input");
        input.type = "text";
        input.size = "60";
        newLi.appendChild(input);
        doc.appendChild(newLI);
     }
 </script>

Solution

  • Typo, it's newLI, not newLi

    <script type="text/javascript">
         function addToList()
         {
            var doc = document.getElementById("myList");
            var newLI = document.createElement("li");
            var input = document.createElement("input");
            input.type = "text";
            input.size = "60";
            newLI.appendChild(input); // typo here, it's not newLi
            doc.appendChild(newLI);
         }
     </script>
    

    FIDDLE