DEV'S

Shopping List App Using IndexedDB

mydb.js


var db;
var DBNAME = "myshoppingAppsss";
var OBJECT_STORE = "myshoppingitems";
var READ_ONLY = "readonly";
var READ_WRITE = "readwrite";
var request = window.indexedDB.open(DBNAME, 1);

request.onsuccess = function(event) {
    db = event.target.result;
    console.log("DB Open successful");
    loadItemsFromStorage();
};

request.onerror = function(event) {
    console.log("Failed to open DB");
};

request.onupgradeneeded = function(event) {
    db = event.target.result;
    var objectStore = db.createObjectStore(OBJECT_STORE, {keyPath: "itemid"});
    //objectStore.add({itemid:1,itemname:"Apple",itemqty:10,itemdesc:""}); // to create table structure
};

shopping.js

var items = []; // empty array 
var c;
var context;
$(document).ready(function() {

});

$(document).on("pagebeforechange", function(ev, dt) {
    if (dt.toPage[0].id === "productpage") {
        var item = dt.options.item;
        if (item.itemid === -1) {
            $("#delBtn").hide(); // Hide the delete button since new item
            $("#saveBtn").html("Add"); // change the save button text to Add
        } else {
            $("#delBtn").show(); // display delete button as it is an exisiting item
            $("#saveBtn").html("Update"); // change the save button text to Update
        }

        $("#itemid").val(item.itemid);
        $("#itemname").val(item.itemname);
        $("#itemqty").val(item.itemqty);
        $("#itemdesc").val(item.itemdesc);
    } else if (dt.toPage[0].id === "myaccount") {
        loadMyAccountFromStorage();
    } else if (dt.toPage[0].id === "mainpage") {

    }
});

$("#mainpage").on("pageshow", function(event) {
    // depricated
});

$(document).on("pageshow", function(event, dt) {
    if (dt.toPage[0].id === "mainpage") {

        if (checkPasscodeLock()) {
            if (sessionStorage.isActive === "NO" || !(sessionStorage.isActive)) {
                $.mobile.pageContainer.pagecontainer("change", "login.html", {transition: "slide"});
            } else {
                if (db) {
                    loadItemsFromStorage();
                }
            }

        } else {
            if (db) {
                loadItemsFromStorage();
            }
        }
    } else if (dt.toPage[0].id === "canvaspage") {
        c = document.getElementById("mycanvas");
        context = c.getContext("2d");
        drawRect();
    }
});

function checkLogin() {
    sessionStorage.isActive = "NO";
    var myAccountValues = {}; // an object
    myAccountValues = JSON.parse(localStorage.myAccountNew);
    var email = $("#email").val();
    var password = $("#password").val();
    console.log(email + "," + password + "," + myAccountValues.email + "," + myAccountValues.password);
    if (email === myAccountValues.email && password === myAccountValues.password) {
        sessionStorage.isActive = "YES";
    } else {
        sessionStorage.isActive = "NO";
    }
    $.mobile.back();

}

function checkPasscodeLock() {
    if (localStorage.myAccountNew) {
        var myAccountValues = {}; // an object
        myAccountValues = JSON.parse(localStorage.myAccountNew);
        if (myAccountValues.lock === "on") {
            return true;
        } else {
            return false;
        }
    }

    return false;
}
function loadItemsFromStorage() {
    items = [];
    var transaction = db.transaction(OBJECT_STORE, READ_ONLY);
    var objectStore = transaction.objectStore(OBJECT_STORE);
    var result = objectStore.openCursor();
    result.onsuccess = function(event) {
        var cursor = event.target.result;

        if (cursor) {
            items.push(cursor.value);
            console.log(cursor.value.itemname);
            cursor.continue();

        }
        prepareList();
    };

}

function prepareList() {
    $("#products").html(""); // Empty the listview
    for (var i = 0; i < items.length; i++) { // recreating it
        $("#products").append('<li><a href="javascript:getItemByItemId(' + items[i].itemid + ')">' + items[i].itemname + '</a></li>');
    }
    $("#products").listview("refresh"); // refresh the listview(control group) with updated values
}

function addNewItem() {

    $.mobile.pageContainer.pagecontainer("change", "addproduct.html", {item: {
            itemid: -1,
            itemname: "",
            itemqty: 0,
            itemdesc: ""
        }, transition: "slide"});
}

function getItemByItemId(itemid) {
    var transaction = db.transaction([OBJECT_STORE], READ_ONLY);
    var objectStore = transaction.objectStore(OBJECT_STORE);
    var result = objectStore.get(itemid);
    result.onsuccess = function(event) {
        $.mobile.pageContainer.pagecontainer("change", "addproduct.html", {item: event.target.result, transition: "slide"});
    };

}

function saveOrUpdateItem() {
    var itemId = $("#itemid").val();
    var itemName = $("#itemname").val();
    var itemQty = $("#itemqty").val();
    var itemDesc = $("#itemdesc").val();
    var item = {};
    var itemIdFloat = parseFloat(itemId); // making sure received item is a number (float type)
    var transaction = db.transaction([OBJECT_STORE], READ_WRITE);
    var objectStore = transaction.objectStore(OBJECT_STORE);
    var result;
    if (itemIdFloat === -1) {
        itemIdFloat = Math.random(); // Unique id for new item
        item = {
            itemid: itemIdFloat,
            itemname: itemName,
            itemqty: itemQty,
            itemdesc: itemDesc
        };
        result = objectStore.add(item);
    } else { // for existing items
        item = {
            itemid: itemIdFloat,
            itemname: itemName,
            itemqty: itemQty,
            itemdesc: itemDesc
        };
        result = objectStore.put(item);
    }

    result.onsuccess = function(event) {
        // update localStorage
        $.mobile.back();
        loadItemsFromStorage();
    };

}

function deleteItemWarning() {
    $("#warning_delete").popup("open");
}

function deleteItem() {
    var itemId = $("#itemid").val();
    var itemIdFloat = parseFloat(itemId);
    var transaction = db.transaction([OBJECT_STORE], READ_WRITE);
    var objectStore = transaction.objectStore(OBJECT_STORE);
    var result = objectStore.delete(itemIdFloat);
    result.onsuccess = function(event) {

        console.log("deleted");
        $.mobile.back();

    };

    $.mobile.back();

}

function loadMyAccountFromStorage() {

    if (localStorage.myAccountNew) {
        var myAccountValues = {}; // an object
        myAccountValues = JSON.parse(localStorage.myAccountNew);
        $("#fullname").val(myAccountValues.fullname);
        $("#email").val(myAccountValues.email);
        $("#password").val(myAccountValues.password);
        $("#female").prop('checked', myAccountValues.isfemale).checkboxradio("refresh");
        $("#male").prop('checked', myAccountValues.ismale).checkboxradio("refresh");
        $("#others").prop('checked', myAccountValues.isothers).checkboxradio("refresh");
        $("#travel").attr('checked', myAccountValues.istravel).checkboxradio("refresh");
        $("#sports").attr('checked', myAccountValues.issports).checkboxradio("refresh");
        $("#business").attr('checked', myAccountValues.isbusiness).checkboxradio("refresh");
        $("#lock").val(myAccountValues.lock).slider("refresh");

    }
}

function saveMyAccount() {
    var fullname = $("#fullname").val();
    var email = $("#email").val();
    var password = $("#password").val();
    var isfemale = $("#female").is(':checked');
    var ismale = $("#male").is(':checked');
    var isothers = $("#others").is(':checked');
    var istravel = $("#travel").is(':checked');
    var issports = $("#sports").is(':checked');
    var isbusiness = $("#business").is(':checked');
    var lock = $("#lock").val();
    sessionStorage.isActive = "NO";
    console.log(isName(fullname));
    if (!isName(fullname)) {
        //alert("Enter valid name");
        $("#validation_result").html("Enter valid name");
        $("#validation_pop").popup("open");
    } else if (!isEmail(email)) {
        //alert("Enter valid email");
        $("#validation_result").html("Enter valid email");
        $("#validation_pop").popup("open");
    } else if (!isPassword(password)) {
        //alert("Password should be minimum 6 letters");
        $("#validation_result").html("Password should be minimum 6 letters");
        $("#validation_pop").popup("open");
    } else {
        localStorage.myAccountNew = JSON.stringify({
            fullname: fullname,
            email: email,
            password: password,
            isfemale: isfemale,
            ismale: ismale,
            isothers: isothers,
            istravel: istravel,
            isbusiness: isbusiness,
            issports: issports,
            lock: lock
        });

        $.mobile.back();
    }

}

function isName(str) {
    //var ptrn = /[a-c]/g; //true for deva; false for dev
    //var ptrn = /[^a-c]/g;  // false for abc ; true for abcd
    //var ptrn = /^abc/g;  // true abcde; false for bcad
    //var ptrn = /abc$/g;  // true efdabc; false for afsasac
    //var ptrn = /^[a-c]/g;  // true for cibi; false for deva
    //var ptrn = /^[a-c0-9]/g; // true for cibi; true for 6deva; false for deva
    //var ptrn = /^[a-z][a-z]+[a-z]$/ig; // true for vasudev; true for Vasudev; false for H.Vasudev; false for vasudev kumar
    //var ptrn = /^[a-z][a-z\s]+[a-z]$/ig; // true for Vasu Dev; true for vasu dev kumaran; false for vasu dev2; false for h.vasu dev
    var ptrn = /^[a-z][a-z\s.]+[a-z]$/ig;
    return ptrn.test(str);

}

function isEmail(str) { // * 0 or more number of matches // + 1 or more number of matches
    var ptrn = /^[a-z0-9][a-z0-9_.\-]*@[a-z0-9]+\.[a-z0-9_.\-]*[a-z0-9]$/g;
    return ptrn.test(str);

}

function isPassword(str) {
    var ptrn = /^[a-z][a-z0-9]{4,}[a-z0-9]$/g; // starting 1+ b/w 4+ end 1 = total 6
    return ptrn.test(str);
}

function isPhone(str) { //xxxxxxxxxx or xxx-xxx-xxxx (x|y)
    var ptrn = /(^[1-9][0-9]{8}[0-9]$)|(^[1-9]{3}\-[0-9]{3}\-[0-9]{4}$)/g; // 10 digit number entered
    return ptrn.test(str);
}

function drawRect() {

    context.fillStyle = "blue";
    context.fillRect(0, 0, 250, 150);  // x,y,width,height
}

function drawLine() {
    context.beginPath();
    context.moveTo(0, 0); // start point (x,y)
    context.lineTo(250, 150); // end point 
    context.stroke();
}

function drawCircle() {
    context.beginPath();
    context.arc(50, 50, 40, 0, 2 * Math.PI);
    context.fillStyle = "red";
    context.fill();
    context.stroke();
}

index.html

<html>
    <head>
        <title>Shopping Page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="js/jquery.mobile-1.4.4.min.css" rel="stylesheet" />
        <script src="js/jquery.min.js" ></script>
        <script src="js/jquery.mobile-1.4.4.min.js" ></script>
        <script src="js/mydb.js"></script>
        <script src="js/shopping.js" ></script>
    </head>
    <body>
        <div data-role="page" id="mainpage">
            <div data-role="header" data-position="fixed" >
                <h1>Shopping List</h1>
                <a href="#right-panel" data-icon="bars" data-iconpos="notext" class="ui-btn-right" >Add</a>
            </div>
            <div role="main" class="ui-content ">
                <ul data-role="listview" id="products" data-inset="true">

                </ul>
            </div>
            <div data-role="panel" id="right-panel" data-theme="b" data-position="right" >

                <ul data-role="listview" data-inset="true"  >
                    <li><a href="javascript:addNewItem()">Add Item</a></li>
                    <li><a href="myaccount.html" data-transition="slide">My Account</a></li>
                    <li><a href="nabarpage.html" data-transition="slide">My Drawings</a></li>
                </ul>

            </div>
            <div data-role="footer" data-position="fixed">
                <h2>Copyrights</h2>
            </div>

        </div>

    </body>
</html>

addproduct.html

<div data-role="page" id="productpage">
    <div data-role="header" data-position="fixed">
        <a href="javascript:deleteItemWarning()" data-icon="delete" id="delBtn" >Delete</a>
        <h2>Add Item</h2>
        <a href="#" data-rel="back" data-icon="back" data-iconpos="notext" class="ui-btn-right">Back</a>
    </div>
    <div data-role="main" class="ui-content">
        <div data-role="fieldcontain" >
            <label for="itemid">ItemID</label>
            <input type="text" name="itemid" id="itemid" readonly/>
        </div>
        <div data-role="fieldcontain">
            <label for="itemname">Item Name</label>
            <input type="text" name="itemname" id="itemname" placeholder="Enter item name"/>
        </div>
        <div data-role="fieldcontain">
            <label for="itemqty">Item Qty</label>
            <input type="number" name="itemqty" id="itemqty" placeholder="Enter quantity" />
        </div>
        <div data-role="fieldcontain">
            <label for="itemdesc">Notes</label>
            <textarea id="itemdesc" name="itemdesc" rows="4" placeholder="Notes">
                
            </textarea>
        </div>
        <button id="saveBtn" onclick="saveOrUpdateItem()">Save</button>

    </div>
    <div data-role="footer" data-position="fixed">
        <h2>Copyright</h2>
    </div>
    <div data-role="popup" id="warning_delete">
        <div data-role="header" data-theme="b">
            <h1>Are you sure?</h1>
            <a href="#" data-rel="back" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Back</a>
        </div>
        <p style="padding: 10px">
            It will be deleted from DB, Data can not be recovered. Do you really want to proceed?
        </p>
        <div data-role="footer" style="text-align: center">
            <a href="#" data-role="button" data-rel="back" >Cancel</a>
            <a href="#" data-role="button" data-icon="check" data-theme="b" onclick="deleteItem();">Delete</a>
        </div>
    </div>
</div>

myaccount.html

<div data-role="page" id="myaccount">
    <div data-role="header" data-position="fixed">

        <h1>My Account</h1>
        <a href="#" data-rel="back" data-icon="back" data-iconpos="notext" class="ui-btn-right">Back</a>
    </div>
    <div data-role="main" class="ui-content">
        <div data-role="fieldcontain">
            <label for="fullname">Name</label>
            <input type="text" id="fullname" name="fullname" placeholder="Enter name" />
        </div>
        <div data-role="fieldcontain">
            <label for="email">Email/Username</label>
            <input type="email" id="email" name="email" placeholder="Enter email here" />
        </div>
        <div data-role="fieldcontain">
            <label for="password">Password</label>
            <input type="password" id="password" name="password" placeholder="Enter password here" />
        </div>
        <div data-role="fieldcontain">
            <fieldset data-role="controlgroup" data-mini="true">
                <legend>Gender</legend>
                <input type="radio" id="female" name="gendergroup" checked />
                <label for="female">Female</label>
                <input type="radio" id="male" name="gendergroup"  />
                <label for="male">Male</label>
                <input type="radio" id="others" name="gendergroup"  />
                <label for="others">Others</label>
            </fieldset>
        </div>
        <div data-role="fieldcontain">
            <fieldset data-role="controlgroup" data-mini="true">
                <legend>Area of Interest</legend>
                <input type="checkbox" id="travel" name="travel"  />
                <label for="travel">Travel</label>
                <input type="checkbox" id="sports" name="sports"  />
                <label for="sports">Sports</label>
                <input type="checkbox" id="business" name="business"  />
                <label for="business">Business</label>
            </fieldset>
        </div>
        <div data-role="fieldcontain">
            <label for="lock">Password Lock</label>
            <select data-role="slider" id="lock" data-mini="true">
                <option value="on">ON</option>
                <option value="off" selected>OFF</option>
            </select>
        </div>
        <button onclick="saveMyAccount()">Save</button>
    </div>
    <div data-role="footer" data-position="fixed">
        <h2>Copyrights</h2>
    </div>
    <div data-role="popup" id="validation_pop" >
        <div data-role="header" data-theme="b">
            <a href="#" data-rel="back" data-icon="delete" data-iconpos="notext">Back</a>
            <h1>Wrong</h1>
        </div>
        <p id="validation_result" style="padding: 10px">Test</p>
    </div>

</div>

login.html

<div data-role="page" id="login">
    <div data-role="header" data-position="fixed">

        <h1>Login</h1>

    </div>
    <div data-role="main" class="ui-content">

        <div data-role="fieldcontain">
            <label for="email">Email/Username</label>
            <input type="email" id="email" name="email" placeholder="Enter email here" />
        </div>
        <div data-role="fieldcontain">
            <label for="password">Password</label>
            <input type="password" id="password" name="password" placeholder="Enter password here" />
        </div>

        <button onclick="checkLogin()">Login</button>
    </div>
    <div data-role="footer" data-position="fixed">
        <h2>Copyrights</h2>
    </div>

</div>

HTML5

2018-11-27 21:35:02
1) Ionic - Angular Videos
2018-06-29 05:46:32
2) Service - Broadcast Receiver
2018-06-28 03:55:43
3) Activity - Bundle - Option Menu - ActionBar
2018-06-27 03:27:57
4) Relative Layout
2018-06-25 03:14:55
5) LinearLayout Calc
2018-02-08 05:14:15
6) PHP HelloWorld
2018-01-19 04:57:25
7) Angular 5 - Material Design - Reactive Form - Continued
2018-01-19 04:06:05
8) Feedback
2018-01-19 02:07:18
9) Angular 5 - Material Design
2018-01-18 03:05:47
10) Angular 5 - Custom Directives,Pipes - Promise And Observables
2018-01-17 22:51:45
11) Angular 5 - Component Interaction
2018-01-17 03:14:26
12) Angular 5 - Registration Form - WebService
2018-01-17 01:46:34
13) Angular 5 - Directives
2018-01-16 23:13:47
14) Angular 5 - Lifecycle Hooks - Routing
2018-01-16 21:36:25
15) CRUD Example - TS - LocalStorage - Delete
2018-01-16 13:34:40
16) Shopping App - Api Calls - JSON
2018-01-16 03:17:09
17) CRUD Example - TS - LocalStorage - View - Add
2018-01-15 23:57:32
18) TypeScript - Part 2
2018-01-15 23:02:07
19) TypeScript - Part 1
2018-01-15 04:46:29
20) TypeScript To JavaScript
2018-01-15 00:48:22
21) First Angular5 App
2016-01-17 23:47:13
22) JQuery Mobile - My Account Page Addon
2016-01-16 02:38:09
23) HTML5 - CSS - JavaScript Exam Preparation
2016-01-14 02:34:08
24) JQuery Validation Plugin - Basics
2016-01-13 02:35:46
25) Final - JQuery Mobile - IndexedDB Addon
2016-01-12 03:23:20
26) JQuery Mobile - IndexedDB Addon
2016-01-11 00:08:42
27) Students Record - JQuery Mobile App
2016-01-09 04:03:04
28) JQuery Mobile PageChange Event
2016-01-08 03:51:55
29) Beginning JQuery Mobile
2016-01-07 03:47:24
30) WebWorker Example
2016-01-06 04:11:18
31) IndexedDB - ObjectStore - Tansaction - Cursor - Part 2
2016-01-05 03:46:35
32) Student Record - IndexedDB Migration
2016-01-04 23:47:55
33) IndexedDB - ObjectStore - Tansaction - Cursor
2016-01-04 04:48:33
34) Single Page Design And Geolocation Example With Ajax
2016-01-03 23:39:19
35) Drag And Drop Example
2016-01-03 01:57:50
36) Beginning Responsive WebDesign Using JQuery
2016-01-03 01:56:17
37) HTML5 Canvas Simple Example
2016-01-03 01:55:11
38) JQuery Object - Context - Function Callbacks
2015-12-29 23:28:49
39) JQuery DOM Manipulation And LocalStorage
2015-11-30 23:50:59
40) JavaScript EventListeners
2015-11-30 04:34:08
41) MultiPage Design
2015-11-28 03:02:52
42) HTML Box Design
2015-07-03 03:09:55
43) KO Custom Component
2015-07-02 23:25:36
44) KO Custom Binding And Template Binding
2015-07-01 23:27:04
45) KO Simplelist
2015-07-01 01:44:40
46) KO Introduction And JQuery Simple List
2015-01-29 00:34:17
47) Canvas - DragDrop - Video - Audio Example
2015-01-28 03:57:05
48) CSS Media Type - IndexedDB WHERE And LIKE Clause
2015-01-27 02:24:12
49) IndexedDB Simple Example
2015-01-24 00:11:32
50) Students Record - JQueryMobile - GeoLocation - Ajax Addon
2015-01-24 00:08:19
51) GeoLocation And Ajax Example
2015-01-21 05:23:32
52) Students Record - JQueryMobile - SessionStorage - Login State
2015-01-19 23:33:29
53) JQueryMobile - Page Change - Popup Addon
2015-01-19 00:21:28
54) JQueryMobile - Data-Role Introduction
2015-01-17 03:22:07
55) Handle PageLinks
2015-01-16 04:28:20
56) Simple HTML5 Calculator
2015-01-16 03:03:45
57) Load External DOM - Ajax In Simple Way
2015-01-16 03:01:48
58) JQuery Document Ready - Placement Of Script Tag
2015-01-13 22:54:25
59) Dynamic Layout Technique Using JQuery
2015-01-13 04:04:19
60) JQuery - Introduction
2015-01-12 23:45:02
61) LocalStorage - CRUD
2015-01-12 00:06:03
62) JSON - LocalStorage Example
2015-01-11 22:47:24
63) JavaScript - Data Persistency Using LocalStorage - SessionStorage
2015-01-10 03:17:01
64) HTML - JavaScript - Dynamic Table
2015-01-10 00:32:26
65) JavaScript Introduction
2015-01-09 04:07:47
66) CSS - Continued
2015-01-08 03:26:39
67) CSS - Margin - Padding - HTML5 Semantic Elements
2015-01-07 22:44:01
68) HTML-CSS Introduction
2014-11-25 14:27:00
69) Angular JS Simple Example
2014-10-16 05:01:39
70) CSS Media Example - Different CSS For Desktop - Tablet - Phone Screen Sizes
2014-10-15 04:20:11
71) Miscellaneous In Addition To Previous Exercises
2014-10-15 04:13:45
72) Some Useful RegEx
2014-10-14 02:57:45
73) Shopping List App Using IndexedDB
2014-10-14 00:04:10
74) IndexedDB Introduction
2014-10-14 00:00:01
75) JavaScript Prototyping
2014-10-11 03:50:47
76) Introduction To Canvas Drawing - Tabs - Popup Warning Dialog
2014-10-11 00:03:50
77) Popup - Validation - Shopping List App Updated
2014-10-10 22:34:42
78) RegEx Pattern For Validation - Shopping List App
2014-10-10 05:12:13
79) Password Lock-Shopping List App
2014-10-09 22:49:34
80) JQuery Shopping - Updated
2014-10-09 05:10:00
81) JQuery Mobile Forms - Save Checkbox - Radio Button Checked States
2014-10-08 22:18:40
82) JQuery Mobile Forms - Additional Data-role Attribute Values
2014-10-08 02:17:48
83) JQuery Shopping List Alternate Approach. JQ Append & Pagechange
2014-10-07 03:02:43
84) JQuery Mobile Page Change Events
2014-10-06 02:19:53
85) JQuery Mobile Data- Attribute Reference
2014-10-06 00:13:01
86) Shopping List Using LocalStorage
2014-10-06 00:10:02
87) JQuery Mobile Introduction
2014-10-06 00:07:40
88) JQuery Page Loading Technique
2014-10-06 00:05:39
89) Mobile Ready Page Extended - Load Multiple Pages Using JQuery
2014-10-06 00:00:27
90) A Mobile First Design Using JQuery - Window-Size
2014-10-05 23:58:01
91) JavaScript Array - Create - Update - Delete
2014-10-05 23:55:43
92) JQuery CSS Capabilities - A Mobile Ready Page
2014-10-05 23:52:42
93) JQuery Introduction - Unit Conversion Using JQuery
2014-10-05 23:49:58
94) JavaScript - DOM Manipulation-Table-Calculator
2014-10-05 23:40:06
95) GeoLocation
2014-10-05 23:37:36
96) Margin And Border Radius
2014-10-05 23:34:06
97) HTML5 Semantic Elements, CSS,SVG Examples
2014-10-05 23:28:45
98) HTML,CSS Selectors

© Vasudev.H / Email: tech3in@live.com