1252748
1252748

Reputation: 15362

jquery data giving error : undefined

On an ajax success function, I put some items into a dropdown using vktemplate. However, I'd like to attach some data to them so that when a user selects the name of an address, I can quickly pull out the whole address from the jquery data object.

This

success: function (returnedData) {

    $('.vendor_address_select').vkTemplate('templates/vendor_addresses_by_sector_dropdown_template.tmpl?<?=time()?>', returnedData, function () {

        $.each(returnedData, function (key, val) {
            var id = val.id;

            //dropdown option looks like this:
            //<option id="vendor_address_id_22">company1</option>
            $('#vendor_address_id_' + id).data('address', {
                'vendorName': val.vendor_name,
                'address1': val.address1,
                'address2': val.address2,
                'city': val.city,
                'state': val.state,
                'zip': val.zip
            });

        });

    });
}

is giving me this error Uncaught TypeError: Cannot call method 'split' of undefined

when i try to access the data like this:

$(document).ready(function () {
    $('.vendor_address_select').change(function () {

        var selectedAddress = $('option:selected', this);
        console.log(selectedAddress.data());

    });
});

How am I misusing jquery's data()?

template file:

<% for ( var i = 0 in o ) { %>
<option id="vendor_address_id_<%=o[i].id%>">
<%=o[i].vendor_name%></option>
<% } %>

Upvotes: 2

Views: 246

Answers (1)

Darcy
Darcy

Reputation: 5368

You have to specify the key 'address' when using .data() like so

$(document).ready(function () {
    $('.vendor_address_select').change(function () {

        var selectedAddress = $('option:selected', this);
        console.log(selectedAddress.data('address'));

    });
});

Upvotes: 4

Related Questions