Saqib Parvaze Saqib Parvaze - 4 months ago 14x
jQuery Question

JavaScript remove Element by Id

Hi i found this code for adding form elements using javascript

var counter = 1;
var limit = 9;
function addFp(spanName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
else {
var newspan = document.createElement('span');
newspan.innerHTML = "<br><b>Implement " + (counter + 1) + " : </b></td><select

name='fp_imp"+(counter+1)+"' class=''><option value='imp1'>Disc Harrow</option><option

value='imp2'>Cultivator</option><option value='imp3'>Disc Harrow</option></select> <input type='text'

name='fp_h"+(counter+1)+"' placeholder='Hours' class='' size='4'> <input type='text' name='fp_t"+(counter

+1)+"' placeholder='Times' class='' size='4'>"

The Html for this code is

<script src="assets/js/field_preparation.js"></script>

<div class="form-top">
<div class="form-top-left">
<h3>Step 1 / 9</h3>
<p>Field preparation:</p>
<div class="form-top-right">
<i class="fa fa-user"></i>
<div class="form-bottom">
<div class="form-group">
<tr><td><b>Tractor Horse Power </b></td><td><b> :</b> </td><td><input type="text" name="tractor" placeholder="HP" class="" size="4"></td></tr>
<tr><td><b>No. of Man Hours </b></td><td> <b> : </b></td><td><input type="text" name="fp_hum" placeholder="Men" class="" size="4"></td></tr>
<span id="dynamicFp">
<tr><td><b>Implement 1</td><td> : </b></td><td><select name="wheat_imp1" class="">
<option value="imp1">Disc Harrow</option>
<option value="imp2">Cultivator</option>
<option value="imp3">Disc Harrow</option></select>
<input type="text" name="wheat_h1" placeholder="Hours" class="" size="4">
<input type="text" name="wheat_t1" placeholder="Times" class="" size="4">

<input type="image" src="./assets/img/plus.png" border="0" width="30px" value="Add Implement" onClick="addFp('dynamicFp');">

The problem i have that is that I want a code to remove the field back if I dont need it as leaving the fields blank will not accept the form.
So, can anyone provide me a code and how to use it to remove back the element. Sorry, I am new to javascript and don't have any idea n the code. Thanks.


Do you wantto remove last addes element? Add new variable at the top of JS

var lastAdded;
var counter = 1;
var limit = 9;

Moddify addFp so it remembers last added span

lastAdded = newspan;

Add new function

function deleteLastAdded () {
  if (lastAdded) {

Add new button

<input type="image" src="./assets/img/plus.png" border="0" width="30px" value="Add Implement" onClick="addFp('dynamicFp');">

<button width="30px" value="Delete last added" onClick="deleteLastAdded();">

Here's the whole code

Edited: btw work on intendation and breaking lines, I fixed it in bin