-1
function AddFileUpload1() {
    if (document.getElementById("FileUploadContainer1").childElementCount < 4) {
        var div1 = document.createElement('DIV');

        div1.innerHTML = '<div id="MyCoolDiv1"><table><tr><td><input id="file' + counter1 + '" name = "file" type="file" accept=".jpg,.jpeg"/></td><td><input id="Button" type="button" value="Remove" Class="btn btn-default" onclick = "RemoveFileUpload1(this)"/></td></tr></table></div>';
        document.getElementById("FileUploadContainer1").appendChild(div1.firstChild);
        counter1++;

    }
}

No matter which button is clicked it removes the first element above code creates control dynamically.

function RemoveFileUpload1(div1) {

    var myCoolDiv1 = document.getElementById("MyCoolDiv1");

    document.getElementById("FileUploadContainer1").removeChild(myCoolDiv1);
}

Above code removes the first element no matter which button is clicked...

vikscool
  • 1,293
  • 1
  • 10
  • 24
Shahid
  • 105
  • 11

1 Answers1

0

You are only able to remove the first element as you are using the id MyCoolDiv1. And as id's are meant to be unique in HTML. So, when you make the query:

var myCoolDiv1 = document.getElementById("MyCoolDiv1");

It is always going to give you the first implementation of the element with the given id (i.e. MyCoolDiv1). So, to have a better understanding on id you can refer to When to use class or id.

and below is an implementation of your function with an optimized approach.

var myTable = document.getElementById('myTable');

function AddFileUpload1() {
  var ChildCount = myTable.querySelectorAll('tr').length;
  var counter = ChildCount + 1;
  if (ChildCount < 4) {
    var tr = document.createElement('tr');
    tr.innerHTML = '<tr><td><input id="file' + counter + '" name = "file" type="file" accept=".jpg,.jpeg"/></td><td><input id="Button" type="button" value="Remove" Class="btn btn-default" onclick = "RemoveFileUpload1(this)"/></td></tr>';
    myTable.appendChild(tr);
  }
}

function RemoveFileUpload1(div1) {
  var get_tr = getParent(div1, 'tr');
  get_tr.remove();
}

function getParent(ele, parent) {
  while (ele.localName != parent) {
    ele = ele.parentElement;
  }
  return ele;
}
<button type="submit" onclick="AddFileUpload1()">
Add
</button>
<div id="FileUploadContainer1">
  <table id="myTable">

  </table>
</div>
vikscool
  • 1,293
  • 1
  • 10
  • 24
  • ..you made my day..can u suggest me some books or website to understand such concepts more clearly as i am new in it.. – Shahid Jun 19 '18 at 10:51
  • most of our knowledge will come only after experience but for practice, you can refer to [W3school](https://www.w3schools.com/jS/default.asp) or you can look at this playlist [kudvenkat](https://www.youtube.com/playlist?list=PL6n9fhu94yhUA99nOsJkKXBqokT3MBK0b) – vikscool Jun 19 '18 at 11:05