Mootools: Add / Remove input from a form using clone
UPDATE: This script was updated, since there was a bug in IE. Thanks Phil for sending this in !
When creating web forms, you will often need to allow multiple entries for a certain input field. Take a look at this example, you will see that it is possible to add/delete an input using Mootools clone function.
First, here is the basic HTML form:
<form name="myForm" action="mootools_row_clone_post.php" method="post"> <div id="input_container" style="padding:10px;"> Example: You can add/delete input fields since you don't kow how many your users will need. <br /> After submitting you will see the resulting array from PHP <div id="div_1"><input type="text" name="my_input[]" id="input_1" size="30" maxlength="30" /> <input class="bt_plus" type="button" value="+" /></div> </div> <div style="padding:10px;"><input type="submit" value="Submit" /></div> </form>
Here are the 2 JavaScript functions that are required for this to work. I have added comments so that you can follow what is being done.
window.addEvent('domready', function() {
$$('input.bt_plus').each(function(el) {
el.addEvent('click', addRow);
});
});
function delRow(el) {
// destroying element
this.getParent().destroy();
}
function addRow() {
// ID of div element that was clicked, with 'div_' removed
clickID = parseInt(this.getParent().get('id').replace('div_',''));
// Generate ID of element to be created
newID = (clickID+1);
// Creating and adding new element
newClone = $('div_'+clickID).clone().injectAfter('div_'+clickID);
// Setting new div's element id
newClone.set('id', 'div_'+newID)
// Making sure the new field does not have a value carried from clone
newClone.getFirst('input').set('value', '');
// Setting new input text id
newClone.getFirst('input').set('id', 'input_'+newID);
// Adding click event on button, it will call addRow function
newClone.getFirst('input').getNext('input').addEvent('click', addRow);
// Changing value of the button that was clicked
this.set('value', '-');
// removing current event that is used to addrow
this.removeEvent('click', addRow);
// adding event to remove row
this.addEvent('click', delRow);
}
That is all that you needs in order to get the add/delete input script working. I find this rather useful when you don’t know the number of times your input will be required by your users.