0

The websites purpose is to store and order book titles, I need to make it so that the user can delete books they have entered into the array. I'm pretty new at Javascript but have a little bit of Java and C# experience.

Little bit stuck on this one. Was doing some reading about removing elements from the array within the code with splice and delete. But when i create a function for it, it removes everything in the array and not just the text box input string.

For the purposes of my assessment it needs to be done without using a third party library.

I'm aware that this is probably not the best way to go about storing data since it clears upon refresh or closing the page.

HTML:

<!DOCTYPE html>
<html>
  <body>
   <h1> Prototype Book Storage and Display </h1>
     <form id = "formWrapper">
     Search<br>
     <input id="myTextBox" type="text" name="search">
     <br>
     <input onClick="submitData()" type="button" value="Submit Book">
     <input onClick="printBooks()" type="button" value="Find Book">
     <input onClick="deleteData()" type="button" value = "Delete Book">
     <p id = "booktitle"></p>
   </form>
  </body>
</html>

Javascript:

  var myFormData = [];   //declare an array
  var value1;

  //Prints My Books to a list
  function printBooks() {
        clearBook();
        alert(myFormData);
        document.getElementById('booktitle').innerHTML = myFormData;

    }
  //Submits input to array
  function  submitData()
  {

   value1 = document.getElementById("myTextBox").value;
   myFormData.push(value1);
   alert(myFormData);
   clearField();
  }

   //Deletes data from the array
  function deleteData()
  {
    deleteValue = document.getElementById("myTextBox").value;
    myFormData.splice(deleteValue);
    alert(deleteValue + " " + "Deleting your book");
  }

  //clears textbox field
  function clearField()
  {
    var txt2 = document.getElementById("myTextBox");
    txt2.value = "";
  }
  //Refreshes book object model
  function clearBook()
  {
   var txt3 = document.getElementById("booktitle");
   txt3.value="";
  }  

1 Answers1

1

The problem is in

myFormData.splice(deleteValue);

splice() expects a starting index, you are passing a string value. See How do I remove a particular element from an array in JavaScript? on how to use it.

In your case it would be

// get the index of the value in the array or -1 if it does not exist
var index = myFormData.indexOf(deleteValue);
// only try removing it, if it exists in the array
if (index !== -1) {
    myFormData.splice(index, 1);
}
masterfloda
  • 2,608
  • 1
  • 12
  • 26
  • Thank you masterfloda, this was really helpful. Solved my problem! It's always the simple stuff that seems to trip me up. Didn't realise this was a duplicate post as well, i guess i didn't really know what i was searching for. – Itz Suno ItzSuno Nov 01 '17 at 03:09