chickensoup
chickensoup

Reputation: 13

Prevent delete of last div in Javascript

I have a slight problem in a feature I am trying to implement on a web page. I have two images, a plus and a minus sign, when plus is clicked it clones a div which consists of a few text box's. The minus image is meant to delete this div.

At the moment, I cannot seem to find a way to stop the last div from being deleted when I click on the minus. I want to just prevent the last row from being deleted and using an alert to inform the user that it cannot be deleted.

Can anyone give me some insight to this? I've searched on here for a while and found something similar, but it's all done using JQuery which I have no experience with.

Here is the code I am using to try and delete the div's.

  function deleteRow1() {

    // row-to-clone1 is the name of the row that is being cloned
    var div = document.getElementById('row-to-clone1');

    if (div) {
        div.parentNode.removeChild(div);
    }

    if ((div).length != 1) {
        alert("Cannot delete all rows.").remove();
    }
}

When I try do delete the row it displays the alert but still deletes the div. I realise this is probably a very easy fix and my implementation of the above may not be correct, if anyone can help I would appreciate it.

Upvotes: 0

Views: 1035

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

ID of an element must be unique, so use a class to fetch them

function deleteRow1() {
  // row-to-clone1 is the name of the row that is being cloned
  var divs = document.getElementsByClassName('row-to-clone1');

  if (divs.length > 1) {
    divs[0].parentNode.removeChild(divs[0]);
  } else {
    alert("Cannot delete all rows.")
  }
}

function add1() {
  var div = document.getElementById('row-to-clone1');
  if (div) {
    var clone = div.cloneNode(true);
    delete clone.id;
    div.parentNode.appendChild(clone);
  }
}
<button onclick="add1()">Add</button>
<button onclick="deleteRow1()">Delete</button>
<div id="row-to-clone1" class="row-to-clone1">div</div>

Upvotes: 2

Related Questions