How can I loop through element's data using jQuery and build these settings?

246 views Asked by At

I'm using MagnificPopup to open a popup form to edit a subscription. I'm passing the values to the form via post, and the values are pulled from the element's data attributes.

The "edit" element that opens popup when clicked:

<a class="editSubscription" href="frmEditSubscription.cfm" 
    data-startdate="#startDate#" data-enddate="#endDate#" data-accounttypeid="#accountTypeID#" 
    data-demo="#demo#" data-comment="#comment#" data-adddate="#adddate#">
        <img src="../images/edit_icon.png" />
</a>

The code to invoke MagnificPopup and pass in all the data attributes:

$('.editSubscription').magnificPopup({
    type: 'ajax',
    preloader: false,
    ajax: {
        settings: {
            type: "POST"
        }
    },

    callbacks:{
        // set data to be posted to popup when loading (can't be done in settings as we need access to current object)
        beforeOpen: function(){
            var instance = $.magnificPopup.instance;
            var currEl = instance.st.el;
            instance.st.ajax.settings.data = {
                startDate: currEl.data("startdate"),
                endDate: currEl.data("enddate"),
                accountTypeID: currEl.data("accounttypeid"),
                demo: currEl.data("demo"),
                comment: currEl.data("comment"),
                addDate: currEl.data("adddate")
            };              
        }   
    }
}); 

This code works; what I'd like to accomplish is to dynamically build the list of values to be passed in the post by looping through all the data attributes, instead of hardcoding.

This code works to loop through the data attributes:

$.each(currEl, function(i, e) {
   alert('name='+ i + ' value=' +e);
});

However, I can't figure out how to use this loop to actually build settings.data. How can I structure this?

1

There are 1 answers

6
Rory McCrossan On

jQuery provides all data attributes on an object when you call the data() method with no parameters. You can then provide this object to the instance. Try this:

beforeOpen: function() {
    var instance = $.magnificPopup.instance;
    var $currEl = $(instance.st.el);
    instance.st.ajax.settings.data = $currEl.data();              
}  

Assuming that instance.st.el provides a jQuery object, you could even shorten this:

beforeOpen: function() {
    var instance = $.magnificPopup.instance;
    instance.st.ajax.settings.data = instance.st.el.data();              
}