简体   繁体   中英

How to fetch existing JSON that exists in data-attr and update that

In the given fiddle , click on Addons buttons and on selection and unselection of Checkboxes , i am trying to update the data-attr array present as data-stuff .

Once i set the data how can i fetch the existing and update it with new data . http://jsfiddle.net/kgm9o693/9/

// checkbox checked
$(document).on('click', '.ui-checkbox-off', function (event) {
    var vendoritemsdata = $(".lastItm_Wrap").data('stuff');
    var checkboxid = $(this).next().attr("id");
    var cost = $(this).attr("cost");
    var toppcrusts = [];
    toppcrusts.push({
        'name': checkboxid,
            'cost': cost
    });
    if (vendoritemsdata.length == 0) {
        $('.lastItm_Wrap').attr('data-stuff', toppcrusts);
    } 
    else {
        var existingdata = $('.lastItm_Wrap').data('data-stuff');
    }
});

Could you please tell me how to resolve this ??

You are trying to use the DOM as a variable. It should be the other way around. Use the DOM only to show results (total cost in your case). But before that keep everything into an array serialize the array if you need it as json or data-stuff.

Examine the example at the bottom of this http://api.jquery.com/serializeArray/

If you want to keep doing it your way, convert the data to JSON and use this:

Set data

$('.lastItm_Wrap').attr('data-stuff', JSON.stringify(toppcrusts) );

Get data

var existingdata = JSON.parse( $('.lastItm_Wrap').attr('data-stuff') );

http://jsfiddle.net/kgm9o693/12/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM