I'm trying to create a form where you can add multiple input fields but also remove each one individually. This is what I got so far:
Html:
<input type="hidden" value="1" id="theValue" />
<div class="form-horizontal vehicleclass0">
<select class="vehicleclass" name="contact['Vehicle0']">
<option value="" style="color: #cecece !important;">--Vehicle type--</option>
<option value="Car">Car</option>
<option value="Truck">Truck</option>
<option value="Boat">Boat</option>
<option value="Tractor">Tractor</option>
</select>
<input type="text" class="vehicleclass" name="contact[Make-Model Vehicle0]" placeholder="Make/Model" autocapitalize="off">
</div>
<div id="myDiv"></div>
<a href="javascript:;" onclick="addElement();"><div class="addvehiclewrapper" id="plus">Add another vehicle</div></a>
Javascript:
function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value - 1) + 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'Vehicle'+ num +'';
newdiv.setAttribute('id', divIdName);
newdiv.innerHTML = '<div class="form-horizontal"><select class="vehicleclass" name="contact[' + divIdName + ']"><option value="" style="color: #cecece !important;">--Vehicle type--</option><option value="Car">Car</option><option value="Truck">Truck</option><option value="Boat">Boat</option><option value="Tractor">Tractor</option></select><input type="text" class="vehicleclass" name="contact[Make-Model ' + divIdName + ']" placeholder="Make/Model" autocapitalize="off"></div> <a href="" onclick="javascript:removeElement('+ divIdName +'); return false">Remove ' + divIdName + '</a>';
ni.appendChild(newdiv);
}
function removeElement(divNum) {
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
}
Everything is working fine, except that when you click remove vehicle it removes all the added input fields at once. What needs to be changed to make it remove only the individual fields?
Thanks for the replies, I removed spaces from the id and added a removeElement function.
It is still not working though. What is missing? Thank you so much