Aaqib Awan
Aaqib Awan

Reputation: 31

Indexeddb OpenCursor returns null on specific key-value

I am working on Indexeddb, I have an objectstore named Items_S1 and KeyPath: "ItemID" I have some orders in the objectstore having ORDERID, ItemID, ItemName, Qty, Rate and NetAmount. While ordering same item again, it increases its quantity.. Now the problem is that when I click a button next to any record to decrease its quantity Nothing happens... same code is working in another project but here I am having problem... I used OpenCursor() but it is returning null. Somebody help Me please, here is the code:

$("#cart_menu").on("click", "#deselect", function(){

    var thisId = $(this).parent().parent().data("key");
    var transaction = db.transaction(["Item_S1"], "readwrite");  
    var objectstore = transaction.objectStore("Item_S1");

    objectstore.openCursor(thisId).onsuccess = function(e){
        var cursor = e.target.result;
        if(cursor){
            if(Number(cursor.value.ItemQty) > 1) {
                objectstore.put({
                        OrderID: cursor.value.OrderID,
                        ItemID: cursor.value.ItemID,
                        ItemName: cursor.value.ItemName,
                        ItemQty: Number(cursor.value.ItemQty) - 1,
                        ItemRate: cursor.value.ItemRate ,
                        ItemAmnt: (Number(cursor.value.ItemQty) - 1) * Number(cursor.value.ItemRate),
                        ItemID: cursor.value.ItemID
                });
            } else {
                objectstore.delete(cursor.value.ItemID);
            }
        }
    };

    transaction.oncomplete = function(){
         displayMenuItem();
    }; 

});

Upvotes: 0

Views: 871

Answers (1)

Aaqib Awan
Aaqib Awan

Reputation: 31

I got a solution to my question... I created index for the objectstore and then used IDBKeyRange.only() Method, it is working perfectly.. Here is the Code,

$("#cart_menu").on("click", "#deselect", function(){

var thisId = $(this).parent().parent().data("key");
var transaction = db.transaction(["Item_S1"], "readwrite");  
var objectstore = transaction.objectStore("Item_S1");
var indexvalue = objectstore.index("By_ItemID");

requestindex = indexvalue.openCursor(IDBKeyRange.only(thisId.toString()));
requestindex.onsuccess = function(){
var cursor = requestindex.result;
if(cursor){

if(Number(cursor.value.ItemQty) > 1)
    {
    objectstore.put({OrderID: cursor.value.OrderID, ItemID: cursor.value.ItemID, ItemName: cursor.value.ItemName, ItemQty: Number(cursor.value.ItemQty) - 1, ItemRate: cursor.value.ItemRate , ItemAmnt: (Number(cursor.value.ItemQty) - 1) * Number(cursor.value.ItemRate), ItemID: cursor.value.ItemID});
    }
    else{
    objectstore.delete(cursor.value.ItemID);
    }
    Total = Number($("#Text1").val()) - Number(cursor.value.ItemRate);
        $("#Text1").val(Total);
}


};

transaction.oncomplete = function(){
     displayMenuItem();
     }; 

});

Upvotes: 2

Related Questions