Proper method for unlimited form inputs in a user interface

- by Jason Lancaster, 2004/12/23

Information

In a properly designed database we're allowed unlimited choices for database assignments, yet html user interfaces are almost always created with a specific number of assignments in mind. This file is intended to resolve the issue and should be used as a reference for a form that can contain an unlimited number of assignments


Working Example



Step by step

  1. The following javascript should be added to the html head.
        <script type="text/javascript" language="Javascript">
        var counter = 0;
        function addnew(){
            counter += 1;
            document.getElementById("data").innerHTML = document.getElementById("data").innerHTML + 
                "<input type=text name=option" + counter +" value=option" + counter + ">" + 
                "<input type=text name=value" + counter + " value=value" + counter + "><br>";
        }
        </script>
    
  2. Start your form.
        <form method=post action="post.php">
    
  3. Create a div that will be used by the javascript for replacement text.
        <div id="data">
    
  4. Hard-code the initial form input line to display, if you so desire.
        <input type=text name=option0 value=option0>
        <input type=text name=value0 value=value0>
        <br>
    
  5. End your div tag so the javascript knows where to end
        </div>
    
  6. Create a submit button.
        <input type="submit" name="submit" value="Add to Database">
    
  7. Create a javascript button that will trigger the addition of a new line.
        <input id="addAnother" type="button" name="addAnother" value="Add Another Line" onclick="javascript:addnew();">