Hi Friends, I would like to share small javascript code which is aimed to provide add more option to your static HTML form. I used this code to provide add more option to add additional fields in my HTML form. It is working great. It might be useful for you.
Open your HTML document and add the following javascript code in your head tag . This code is to create and remove dynamic div for HTML document.
Javascript function to create dynamic div:
//Function to add Dynamic div function addElement() { var ni = document.getElementById('myDiv'); var numi = document.getElementById('theValue'); var num = (document.getElementById("theValue").value -1)+ 2; numi.value = num; var divIdName = "my"+num+"Div"; var newdiv = document.createElement('div'); newdiv.setAttribute("id",divIdName); newdiv.innerHTML = " <table> <tbody> <tr> <td>View:</td> <td><input id="views[]" name="views[]" type="text" /></td> </tr> <tr> <td>Before:</td> <td><input id="before[]" name="before[]" type="file" /></td> </tr> <tr> <td>After:</td> <td><input id="after[]" name="after[]" type="file" /></td> </tr> <tr> <td><a onclick="\"removeElement(\'"+divIdName+"\')\"" href="\">Remove</a></td> </tr> </tbody> </table> "; ni.appendChild(newdiv); } |
Javascript function to remove dynamic div by passing its id:
//Function to remove dynamic div function removeElement(divNum) { var d = document.getElementById('myDiv'); var olddiv = document.getElementById(divNum); d.removeChild(olddiv); var numi = document.getElementById('theValue'); numi.value = numi.value - 1; } |
Simple HTML form:
<form name="f" method="post" enctype="multipart/form-data"> <input type="hidden" value="0" id="theValue" name='theValue'/> <p><a href="javascript:;" onClick="addElement();">Add More</a></p> <div id="myDiv"> <script type="text/javascript">addElement(); </script></div> <input type="submit" name="submit" id="submit" value="submit" /> </form> |