shifter480
Technical User
Hi,
I currently have some JS that allows me to dynamically add input boxes. Once submitted each dynamically added box value is added to an array.
I want to add a button that will allow me to delete the last dynamically added box.
Here is my attempt
<script language="javascript" type="text/javascript" defer>
// This function will dynamically add level fields to the form.
var counter = 1;
var limit = 10;
function addInput(divName)
{
if (counter == limit)
{
alert("You have reached the limit of adding " + counter + " inputs");
}
else
{
counter++;
var newdiv = document.createElement('div' + (counter));
newdiv.innerHTML = "<label>Level"+ (counter)+ ": *</label><input type='text' name='levels[]'>";
document.getElementById(divName).appendChild(newdiv);
}
}
function remove(id)
{
return (elem=document.getElementById(id)).parentNode.removeChild(elem);
}
function removeInput(divName)
{
if (counter > 1)
{
remove('div' + (counter));
--counter;
}
}
</script>
The HTML buttons:
<hr/>
<div id="dynamicRemove">
<input type="button" value="Remove level" onClick="removeInput('dynamicRemove');">
</div>
<div id="dynamicInput">
<label>Level1: *</label> <input type="text" name="levels[]">
<input type="button" value="Add level" onClick="addInput('dynamicInput');">
</div>
<hr/>
The adding works but the remove doesn't. Any ideas would be much appreciated.
Thanks
I currently have some JS that allows me to dynamically add input boxes. Once submitted each dynamically added box value is added to an array.
I want to add a button that will allow me to delete the last dynamically added box.
Here is my attempt
<script language="javascript" type="text/javascript" defer>
// This function will dynamically add level fields to the form.
var counter = 1;
var limit = 10;
function addInput(divName)
{
if (counter == limit)
{
alert("You have reached the limit of adding " + counter + " inputs");
}
else
{
counter++;
var newdiv = document.createElement('div' + (counter));
newdiv.innerHTML = "<label>Level"+ (counter)+ ": *</label><input type='text' name='levels[]'>";
document.getElementById(divName).appendChild(newdiv);
}
}
function remove(id)
{
return (elem=document.getElementById(id)).parentNode.removeChild(elem);
}
function removeInput(divName)
{
if (counter > 1)
{
remove('div' + (counter));
--counter;
}
}
</script>
The HTML buttons:
<hr/>
<div id="dynamicRemove">
<input type="button" value="Remove level" onClick="removeInput('dynamicRemove');">
</div>
<div id="dynamicInput">
<label>Level1: *</label> <input type="text" name="levels[]">
<input type="button" value="Add level" onClick="addInput('dynamicInput');">
</div>
<hr/>
The adding works but the remove doesn't. Any ideas would be much appreciated.
Thanks