How To Insert, Search, Delete An Item In Javascript Array
In This Javascript Tutorial we will see How To Add, Find And Remove Item In An Array Using JS Using Netbeans Editor .
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript: Add - Search - Remove Array Element</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// create an array
var myArr = ["AA","BB","CC","DD","EE","FF","GG"];
// add element to the array
function addElement()
{
// get the input value
var txt = document.getElementById('txt').value;
// add the value to the array
myArr.push(txt);
// display the array elements in p
document.getElementById('pgh').innerHTML = myArr;
}
// search and delete array element
function searchAndDeleteElement()
{
// get the input value
var txt = document.getElementById('txt').value;
// get the value index on the array
var index = myArr.indexOf(txt);
// if the element exist
if(index !== -1 )
{
// remove the element from the array
// splice(start index, count)
myArr.splice(index,1);
document.getElementById('pgh').innerHTML = myArr;
}
// if the element not exist
else{
alert("Not Found");
}
}
</script>
</head>
<body>
<input type="text" name="txt" id="txt"/>
<p id="pgh"></p>
<button onclick="addElement();">Push</button>
<button onclick="searchAndDeleteElement();">search And Delete</button>
<script>
document.getElementById('pgh').innerHTML = myArr;
</script>
</body>
</html>
1 comments:
commentsGreat post thanks for sharing!
Reply