How to remove a JSON object from localStorage according to the data assigned to the current click element?

Scenario

  • The user clicks on the item, the background image of this item has been changed, and the data assigned to this item (attribute onclick) is inserted into localStorage: this part works fine.
  • Now the variable is toggleset to 0, the background image is changed and the data is deleted from the local storage: this part works fine.

  • ...

  • The user clicks on another element (first click data is deleted from the previous div). although in this case you need to insert new data, but is it not?

Json data:

 Object {
    sess_id   : 182104, 
    name      : "AUTOMECH FORMULA", 
    city      : "Cairo", 
    country   : "Egypt", 
    event_url : "automech-formula"
}

events:189 Object {
    sess_id   : 182104, 
    name      : "AUTOMECH FORMULA", 
    city      : "Cairo", 
    country   : "Egypt", 
    event_url : "automech-formula"
}

snapshot (for all data deleted by a single clicked item): -

enter image description here

HTML:

<div class="evt_date"  style="overflow:hidden" style="overflow:hidden" itemscope itemtype="http://schema.org/Event">                             
    <a href="javascript:void(0);"  class="favourate_dextop" id="fav'.$data[$k]['id'].'"  onClick=" favaorite('.$data[$k]['id'].',\''.$name_event.'\',\''.$event_city.'\',\''.$event_country.'\',\''.$event_urls.'\',this)"></a>
</div>

JavaScript:

var image2 = 'http://im.gifbt.com/images/star1_phonehover.png';
var image1 = 'http://im.gifbt.com/images/star1_phone.png';
var toggle = 1;

function favaorite(sess_id,name,city,country,event_url,pointer){
    var eventData;
    //is anything in localstorage?
    if (localStorage.getItem('eventData') === null) {
        eventData = [];
    }else{
        // Parse the serialized data back into an array of objects
        eventData = JSON.parse(localStorage.getItem('eventData'));
        console.log(eventData);   
    }
    var details={};
    details.sess_id   = sess_id;
    details.name      = name;
    details.city      = city;
    details.country   = country;
    details.event_url = event_url;

    // Push the new data (whether it be an object or anything else) onto the array
    eventData.push(details);

    if (toggle == 1){
        console.log("1");
        $(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + image2 + '")');
        toggle = 0;
    }else{
        console.log("2");
        $(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + image1 + '")');
        $.each(eventData, function(key, value){
            console.log(value);
            //$('#fav'+ delete value.sess_id + '');
            //$('#fav'+ delete value.name + '');
            //$('#fav'+ delete value.city + '');
            //$('#fav'+ delete value.country + '');
            //$('#fav'+ delete value.event_url + '');
            delete value.sess_id;
            delete value.name;
            delete value.city;
            delete value.country;
            delete value.event_url;            
            //localStorage.removeItem(value.sess_id);

        });
        toggle = 1;
    }
    // Alert the array value
    // alert(eventData);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    var jsondata=localStorage.setItem('eventData', JSON.stringify(eventData));
    console.log(jsondata);
}

Fiddle

+4
1

, JSON.stringify javascript:

eventData = [];

, : eventData = {};

- :

delete value.sess_id;
delete value.name;
delete value.city;
delete value.country;
delete value.event_url;

, . : {}{}{}{}{}... ( ). , , ((*), . )


/:

  • onclick jQuery .click().

  • data - , ( ).

  • toggle , . / . .toggleClass() CSS ( ).

  • (*) localStorage , . ( "" ) . id , , :
    fav1:{name :'blah', ...}, fav2:{...}, ...

HTML:

<a href="#" class="favourate_dextop" id="fav'.$data[$k]['id'].'"
    data-sess_id="'.$data[$k]['id'].'"
    data-name="'.$name_event.'"
    data-city="'.$event_city.'"
    data-country="'.$event_country.'" 
    data-event_url="'.$event_urls.'" >
</a>

JQuery

$(document).ready(function(){

    // declare an empty object (not array):
    var eventData = {};
    // check localStorage first after the page is ready (not on click):
    if (localStorage.getItem('eventData') !== null) {
        // if there any faved link in the localstorage, highlight it:
        $.each(eventData = JSON.parse(localStorage.getItem('eventData')), function(id){
            $('#'+id).addClass('faved');
        });
    }

    // instead of 'onclick' attribute, use jQuery .click() event handler:
    $('.favourate_dextop').click(function(e){
        // prevent default link click (instead of using "javascript:void(0);" in a href attribute):
        e.preventDefault();
        // check if the link "id" attribute (this.id) exists in the object:
        if (eventData[this.id] !== undefined) {
            // if so, delete it:
            delete eventData[this.id];
        }else{
            // if not, add it:
            // the .data() method gets all 'data' attributes of the element (as an objct) 
            eventData[this.id] = $(this).data();
        }
        // toggle '.faved' class:
        $(this).toggleClass('faved');
        // update localstorage:
        localStorage.setItem('eventData', JSON.stringify(eventData));
    });     
});

.faved CSS jQuery:

.favourate_dextop.faved, .favourate_dextop:hover{
    background:url('http://im.gifbt.com/images/star1_phonehover.png') no-repeat;
}

JSFiddle

+2

All Articles