V
V
valitskiydmitriy2015-10-20 12:47:23
JavaScript
valitskiydmitriy, 2015-10-20 12:47:23

Executing a js function on a specific page?

There is this function:

window.onload = function () {
    var day = new Date,
        md = (new Date(day.getFullYear(), day.getMonth() + 1, 0, 0, 0, 0, 0)).getDate(),
        $month_name = "января февраля марта апреля мая июня июля августа сентября октября ноября декабря".split(" ");

    function set_select(a, c, d, e) {
        var el = document.getElementsByName(a)[0];
        for (var b = el.options.length = 0; b < c; b++) {
            el.options[b] = new Option(a == 'month' ? $month_name[b] : b + d, b + d);
         }
        el.options[e] && (el.options[e].selected = !0)
    }
    set_select("day", md, 1, day.getDate() - 1);
    set_select("month", 12, 1, day.getMonth());
    set_select("year", 50, day.getFullYear()-50, 50);


    var year = document.getElementById('year');
    var month = document.getElementById("month");

    function check_date() {
        var a = year.value | 0,
            c = month.value | 0;
        md = (new Date(a, c, 0, 0, 0, 0, 0)).getDate();
        a = document.getElementById("day").selectedIndex;
        set_select("day", md, 1, a)
    };

    if (document.addEventListener) {
        year.addEventListener('change', check_date, false);
        month.addEventListener('change', check_date, false);

    } else {
        year.detachEvent('onchange', check_date);
        month.detachEvent('onchange', check_date);
    }

}

On all pages except the registration page, there is an error.
Cannot read property 'options' of undefined
For everyone, I tried to run it only on the registration page, it doesn’t work out in any way, how best to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2015-10-20
@valitskiydmitriy

Obviously, the problem is in the set_select function - when the element with the specified name is not on the page, it crashes with an error. Simply checking for the existence of an element is enough:

function set_select(a, c, d, e) {
    var el = document.getElementsByName(a)[0];

    if (!el) {
        console.warn('Element "' + a + '" not found');
        return;
    }

    for (var b = el.options.length = 0; b < c; b++) {
        el.options[b] = new Option(a == 'month' ? $month_name[b] : b + d, b + d);
    }

    el.options[e] && (el.options[e].selected = !0)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question