Link to home
Start Free TrialLog in
Avatar of Victor Kimura
Victor KimuraFlag for Canada

asked on

jQuery $.each not working for array

Hi,

I have this bit of js code that grabs all the keys and values for a form:

    $.fn.calculate_selections.get_all_selections = function() {
        var inputData = new Array();

        $("#get_all_selections").find('input[type="text"]').each(
            function (unusedIndex, child) {
                inputData[child.name] = child.value;
            });

        $("#get_all_selections").find('input[type="hidden"]').each(
            function (unusedIndex, child) {
                inputData[child.name] = child.value;
            });

        $("#get_all_selections").find('input[type="radio"]:checked').each(
            function (unusedIndex, child) {
                inputData[child.name] = child.value;
            });

        $("#get_all_selections").find('select option:selected').each(
            function (unusedIndex, child) {
                var oClosest = $(this).closest('select');
                var sName = oClosest.attr('name');
                inputData[sName] = child.value;
            });

        $("#get_all_selections").find('textarea').each(
            function (unusedIndex, child) {
                inputData[child.name] = child.value;
            });
        return inputData;

    }

Open in new window


I return it from a plugin:
var aInputDataVals = $('').calculate_selections.get_all_selections();

Open in new window


But this part doesn't work:
    $.each(aInputDataVals, function (key, value) {
        calculate_final_amount(key, value);
    });

Open in new window


What am I doing wrong? I'm trying to debug in Chrome and it's not stepping into the $.each(). I can see aInputDataVals is an array of keys and values.

aInputDataVals['test'] = 1;
ASKER CERTIFIED SOLUTION
Avatar of Mrunal
Mrunal
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Victor Kimura

ASKER

Hi Mrunai,

Yes, if I use the array like in your example var arr then I found the indexes are 0, 1, 2, etc.

but the function I have must use var obj = {} like in your example since it's actually an object not an array that is created I think. Anyways, changing the line from:

var inputData = new Array();

to:

var inputData = {};

does the trick.

Thank you! =)