JSFiddle - React, Tailwind, and code Playground
by Sillvva
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="readAll">ReadAll</button>
<button id="add">Add</button>
JavaScript
const employeeData = [
{ id: "01", name: "Gopal K Varma", age: 35, email: "[email protected]" },
{ id: "02", name: "Prasad", age: 24, email: "[email protected]" }
];
var db;
var version = 1;
var request = window.indexedDB.open("newDatabase", version);
request.onerror = function(event) {
console.log("error: ", event.target.error);
};
request.onsuccess = function(event) {
db = request.result;
console.log("success: ", db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("employee", {keyPath: "id"});
for (var i in employeeData) {
objectStore.add(employeeData[i]);
}
}
function add() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.add({ id: "03", name: "Prasad", age: 24, email: "[email protected]" });
request.onsuccess = function(event) {
alert("Prasad has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nPrasad is already exist in your database! ");
}
}
function readAll() {
var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
cursor.continue();
} else {
alert("No more entries!");
}
};
}
$(document).ready(function() {
document.getElementById("readAll").addEventListener("click", readAll);
document.getElementById("add").addEventListener("click", add);
})