Cannot read property 'indexOf' of undefined

Lukeluha picture Lukeluha · Jul 23, 2014 · Viewed 67.5k times · Source

i'm trying to set different options for several datepickers in jquery. My code is looks like this:

{foreach $cart->getItems() as $item}
    {if $item->action->prereservation}
        var disableDates = new Array();
        {if $item->action->hasVariants()}
        disableDates[{!$item->id}] = {$disabledDates[$item->action->id][$item->idVariant]};
        {else}
        disableDates[{!$item->id}] = {$disabledDates[$item->action->id]};
        {/if}

        if (disableDates[{!$item->id}].length !== 0) {
            $(".datepicker_"+'{$item->id}').datepicker({
                maxDate: new Date('{!$item->action->voucherTo|date: Y-m-d}'),
                beforeShowDay: function(date){
                    var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                    console.log(disableDates[{!$item->id}]) // result is undefined (but not for last iteration)
                    return [ disableDates[{!$item->id}].indexOf(string) == -1 ]
                }
            })
        } else {
            $(".datepicker_"+'{$item->id}').datepicker({
                maxDate: new Date('{!$item->action->voucherTo|date: Y-m-d}'),
            })
        }
    {/if}
{/foreach}

but if there is more than one item in foreach, my js console show error Cannot read property 'indexOf' of undefined for the first iteration, only last is good. Can anybody help me please?

In my code Im combining template system Latte and jquery.

This is my final code in browser:

var disableDates = new Array();
        disableDates[777955] = ["2014-07-25","2014-07-26","2014-07-27","2014-07-28","2014-07-29","2014-07-30","2014-07-31"];

        if (disableDates[777955].length !== 0) {
            $(".datepicker_"+'777955').datepicker({
                maxDate: new Date('2014-07-31'),
                beforeShowDay: function(date){
                    var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                    return [ disableDates[777955].indexOf(string) == -1 ]
                }
            })
        } else {
            $(".datepicker_"+'777955').datepicker({
                maxDate: new Date('2014-07-31'),
            })
        }

Thanks for any advices

Answer

epascarello picture epascarello · Jul 23, 2014

If you are doing that in a loop, you keep overriding the array!

var disableDates = new Array();
disableDates[123] = 123;
console.log(disableDates[123]);  //123

var disableDates = new Array();
disableDates[456] = 456;
console.log(disableDates[123]);  //undefined

Move the array declaration outside of the loop or check if it exists before creating a new Array.