I was developing a localstorage crud operation. I stored the data's using a table. It works perfectly fine. In the action Delete button is set to delete the key value of the local storage. The button onclick is working with other function. But not working with the function cleardata.
Visit fiddle to see the code
https://jsfiddle.net/saif_lesnar/vkwgq5z9/1/
<html>
<head>
<style>
table,th,td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<script src="local.js"></script>
</head>
<body >
<section >
<form>
<p>User Name:<br> <input type="text" id= "key"/></p>
<p>User Number:<br><input type="number" id="value"/></p>
<p>User Address:<br><input type="text" id="data"/></p>
<p><input type="submit" id= "button" value="Submit"/></p>
</form>
</section>
<table id="display_data">
<tr>
<th>
User Name
</th>
<th>
User Number
</th>
<th>
User Address
</th>
<th>
Action
</th>
</tr>
</table>
</body>
</html>
Heres the js code
function doFirst(){
var button = document.getElementById('button');
button.addEventListener("click",save,false);
display();
}
function save(){
var key = document.getElementById("key").value;
var value = document.getElementById("value").value;
var data = document.getElementById("data").value;
var obj=[
value,data
];
localStorage.setItem(key, JSON.stringify(obj));
display();
key.value="";
value.value="";
data.value="";
}
function display(){
var display_data = document.getElementById("display_data");
for(var i = 0; i <localStorage.length; i++){
var a = localStorage.key(i);
var b = JSON.parse(localStorage.getItem(a));
console.log(a);
display_data.innerHTML +="<tr><td>"+a+"</td><td>"+b[0]+"</td><td>"+b[1]+"</td><td><button onclick='cleardata("+a+")' type='button'>Delete</button></td></tr>";
}
}
function cleardata(data){
console.log(data);
localStorage.removeItem(data);
location.reload();
}
window.addEventListener("load",doFirst,false)
Please help me out.