// you’re reading...

Technology

DOM-inating dynamic form elements

Objective:
Create an HTML form with a text field and allow users to add up to a fixed number of additional text input fields dynamically w/o refreshing.

This is probably the simplest things in the world for javascript gurus, but since I’m not, I found it difficult to accomplish even with examples found on Google.

Javascript:

var counter = 1;
var limit = 3;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
         var elementname = 'inputfield_' + (counter + 1);
         var newdiv = document.createElement('div');
         newdiv.setAttribute('id', elementname);
          newdiv.innerHTML = "<div class='inputfields'>Entry " + (counter + 1)
                + " <input type='text' name='textinput[]'>"
                + "<a href='#' onclick=\"javascript:removeInput("
                + "'" + divName + "'"
                + ","
                + "'" + elementname + "'"
                + ");\">remove</a></div>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}
function removeInput(divName,childName){
    try {
        childdiv = document.getElementById(childName);
        document.getElementById(divName).removeChild(childdiv);
    } catch (e) {
        alert(e);
    }

    counter--;
}

HTML:

<form>
<div id="inputs">
<div>Input Name: <input class="inputfields" name="textinput[]" type="text" /></div>
</div>
<div id="buttons"><input id="btn_add_more" onclick="javascript:addInput('inputs');" type="button" value="Add" /></div>
</form>

Example:
http://www.randymelder.com/test/form_auto_add_textfields.php

Many thanks to my two sources for parts of this exercise here and here.

Discussion

No comments for “DOM-inating dynamic form elements”

Post a comment



 

September 2009
S M T W T F S
« Jul   Dec »
 12345
6789101112
13141516171819
20212223242526
27282930