-1
    for(i=0; i<=entryArray.length; i++) {
        $(colorChange[entryArray[i]]['textfield']).ColorPicker({
            color: "FFFFFF",
            onChange: function (hsb, hex, rgb) {
                $(colorChange[entryArray[i]]['textfield']).val("#" + hex);
                $(colorChange[entryArray[i]]['className']).css(colorChange[entryArray[i]]['cssEntry'], "#" + hex);
            }
        })
    }

I got this error : Uncaught TypeError: Cannot read property 'textfield' of undefined

Ajay2707
  • 5,690
  • 6
  • 40
  • 58
iSeven
  • 35
  • 7

1 Answers1

1

Problem is in combination of for loop and function definition.

$(colorChange[entryArray[i]]['textfield']).val("#" + hex);

onChange function captures reference to i variable. Not the value itself.

Code can be fixed like this:

entryArray.forEach(function (entry) {
        $(colorChange[entry]['textfield']).ColorPicker({
                color: "FFFFFF",
                onChange: function (hsb, hex, rgb) {
                        $(colorChange[entry]['textfield']).val("#" + hex);
                        $(colorChange[entry]['className']).css(colorChange[entry]['cssEntry'], "#" + hex);
                }
        });
});

See this question for more details.


I also should mention problems with for loop itself.

for (i = 0; i <= entryArray.length; i++)
  • <= incorrect in this case. You eventually end up with i === entryArray.length, while last element in the array has index entryArray.length - 1. Use <.
  • i escapes from current scope and goes directly to the global (always use var i = 0;, unless you want to reuse some local variable)
Community
  • 1
  • 1
sigod
  • 3,514
  • 2
  • 21
  • 44