-2

<code>
<!DOCTYPE html>
<html>
 <head>
  <title>Java Script Array methods</title>
  <script type="text/javascript">
  
  var ArrStr = ["Yallappa","Rajesh","Kiran"];
  function LoadArr(){
   document.getElementById("Arr").innerHTML = ArrStr;
  }
  
  function But1Click(){
   
   ArrStr.push(document.getElementById("TxtBox").value);
   document.getElementById("Arr").innerHTML = ArrStr;
  }
  
  function But2Click(){
   var Indx = ArrStr.indexOf(document.getElementById("Arr").value);
   alert(Indx);
   if(indx > -1){
    arrstr.splice(document.getelementbyid("arr").value,1);
   }
   document.getelementbyid("arr").innerhtml = arrstr;
  }
  
  </script>
 </head>
 <body onLoad="LoadArr()">
  <h2 id="Arr"></h2><br>
  <input type="text" id="TxtBox"/><br>
  <input type="button" onclick="But1Click()" text="Push into Array" value="Push into Array"/><br>
  <input type="button" onclick="But2Click()" text="Remove from Array" value="Remove From Array"/>
  
 </body>
</html>
</code>
I wanted to add and remove text from the textbox based on the button click events. And display the array of strings in h2 tag. In this I am able to add a new string in array, but I am not able to remove string. Why please explain me?

1 Answers1

0

In But2Click method change arrstr to ArrStrand indx to Indx Your But2Click is full of errors. It should be as given below:

function But2Click(){
            var Indx = ArrStr.indexOf(document.getElementById("TxtBox").value); //id here should be of textbox
            alert(Indx);
            if(Indx > -1)//case of variable was incorrect
            {
                ArrStr.splice(Indx,1); //splice function needs index as first argument
            }
            document.getElementById("Arr").innerHTML = ArrStr;//id was incorrect and case in variable name was incorrect
        }
Akshey Bhat
  • 7,535
  • 1
  • 16
  • 20