Not all forms are meant to be static. Sometimes, you want to allow the users to add certain parts of the form as they need them. Here is a nice example of dynamically adding inputs to your form as users need them. In addition, an input limit has been implemented in the script and it is set to 3.
Here I will explain it by the HTML coding:
Code:
<script src="/wp-includes/js/addInput.js" language="Javascript" type="text/javascript"></script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><input type="text" name="myInputs[]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
</form>
When the user clicks on the Add another text input button, the addInput JavaScript function is executed and given the dynamicInput argument which is the name of the div that contains all our text inputs. Here is what our JavaScript function looks like:
Code:
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Bookmarks