1

I have a form with inputs using an array for the name like this:

<input type="text" name="answer[0]" />

Those work fine when I do an ajax post and serialize the form for the data. Now I am trying to pass a dynamic object to jQuery ajax data that will mimic the structure it gets if it were to serialize the form. Here is the code I'm trying for that:

function sliderCalc(){
        var step = jQuery('[name="step"]').val();
        var max = jQuery('[name="max"]').val();
        var min = jQuery('[name="min"]').val();
        var count = (max - min) / step;
        var sliderData = {};
        for(i=0; i<=count; i++){
            var value = min + (step * i);
            sliderData.answers[i] = value; // key => value created here
        }
        return sliderData;
    }

I'm getting this error:

Uncaught TypeError: Cannot set property '0' of undefined

Does anyone have a good solution for this?

2
  • What's the exact error message you are getting? Commented Sep 21, 2012 at 19:24
  • Added the error message to bottom Commented Sep 21, 2012 at 19:30

2 Answers 2

1

You need create answers property first of assigning array elements:

sliderData.answers = new Array();
Sign up to request clarification or add additional context in comments.

2 Comments

That worked, thanks! I figured it would work same as var array[] = (1, 2, 3);
Better to use [] over new Array()
0

this would be a proper way to create sliderData

    var sliderData = { answers: [] };
    for(i = 0; i <= count; i++) {
        var value = min + (step * i);
        sliderData.answers[i] = value; 
    }

complete code:

function sliderCalc() {
    var
        step = jQuery('[name="step"]').val(),
        max = jQuery('[name="max"]').val(),
        min = jQuery('[name="min"]').val(),
        count = (max - min) / step,
        sliderData = {
            answers: []
        },
        value = 0;

    for (i = 0; i <= count; i++) {
        value = min + (step * i);
        sliderData.answers[i] = value; // key => value created here
    }
    return sliderData;
}​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.