Question

this looks simple enough but I just can't get it to work. I could add DOM elements but I just can't remove them when using an array.

<script language="javascript">
fields = 0;
count = 0;
function addInput() {
  if (fields != 10) {
      var htmlText =  "<input type='search' value='' name='field[]' />";
      var remButton = "<input type='button' value='del' onclick='remove()' />";
      var newElement = document.createElement('div');

      newElement.id = 'SomeID'+fields; 
      newElement.innerHTML = htmlText + remButton + newElement.id;

      var fieldsArea = document.getElementById('text');
      fieldsArea.appendChild(newElement);

      fields += 1;
  } else {
     ...
  }
count++;
}

// NEED HELP FROM HERE PLEASE
// You don't need to Loop, just get the button's id and remove that entire 'SomeID'


function remove() {
  fieldsArea = document.getElementById('text');


  fieldsArea.removeChild(SomeID1);   <-----------------------THIS WORKS!
  fieldsArea.removeChild(SomeID+count); <------------------THIS JUST WOULDN'T

  count--;
}
</script>

In the remove function, writing SomeID1 works and delete the first added element but when I try to use a 'count', I just can't delete my 'elements'.

Any help would be most appreciated.

Thank you!

Was it helpful?

Solution

You have to get a reference to the element first. Currently you are passing an undefined variable SomeID to the function.

E.g.:

var element = document.getElementById('SomeID' + fields);
// or starting by zero: var element = document.getElementById('SomeID0');
element.parentNode.removeChild(element);

If you want to remove the div for which the button was clicked, you have to pass a reference to the corresponding div to the remove function.

'<input type="button" value="del" onclick="remove(this.parentNode)" />';

this will refer to the button and as it is a child of the div, this.parentNode refers to that div.

You also have to change your function to accept the element that should be removed:

function remove(element) {
  element.parentNode.removeChild(element);   
  count--;
}

You probably also have to update fields, but I'm not sure how your code is supposed to work.


If you want to remove all of them you have to loop:

for(;fields--;) {
   var element = document.getElementById('SomeID' + fields);
   element.parentNode.removeChild(element);
}

Also have a look at the documentation of removeChild.

OTHER TIPS

The removeChild needs a node (DOM element) as parameter. In this case

fieldsArea.removeChild(SomeID+count);

you could for example pass the node this way

fieldsArea.removeChild(document.getElementById('SomeID'+count));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top