Search code examples
javascripthtmlfunctionif-statementconfirmation

How can I prevent an confirmation from being called through a certain action?


I have the following code:

var noteName;
function reset() {

confirmation = confirm("Are you sure you'd like to delete " + noteName + "?");
  if(confirmation === false) {
  alert("Deletion Cancelled");
}
else if(localStorage.getItem('savetext') === null) {
  alert("There is nothing to delete");
}
else {
   alert("Delete Successful");
   localStorage.removeItem('savetext');
  document.getElementById("confirmation-Here").innerHTML = "Deleted";
 }
}

What I'm trying to do is, if a user presses a delete button, it'll output a confirmation alert where the user has the choice to cancel (false) or continue with the action by pressing okay (true). However, while that does work, the issue comes in when the local storage is already empty, it's annoying to see the same user popup appear that says "Are you sure you'd like to delete undefined?" Undefined being because after saving, I've set it up so the user can name their saved text. But by deleting the text via local storage, the name itself has been deleted so it returns as undefined. The thing is, I don't want that shared popup to appear if the local storage is empty and it saying undefined. I just want it to alert: "There is nothing to delete". And that's all. The variable "noteName" has been defined earlier in the code**

I can't think of a way to restructure my code so that the confirmation alert doesn't return when there's nothing in the local storage. How can I go about this? How should I change this code?


Solution

  • try this code

    function reset() {
      if (!localStorage.getItem("savetext")) return;
    
      confirmation = confirm("Are you sure you'd like to delete " + noteName + "?");
      if (!confirmation) {
        alert("Deletion Cancelled");
      } else {
        alert("Delete Successful");
        localStorage.removeItem("savetext");
        document.getElementById("confirmation-Here").innerHTML = "Deleted";
      }
    }