[Solved] Javascript can’t pass parameters between functions


Code in onXyz attributes is run at global scope, so both of your examples require that there be a global variable called artist. If there isn’t one, then you’ll get a ReferenceError because you’re trying to take the value of a symbol that isn’t defined.

If you meant to pass a string, put quotes around it. If you meant to pass something else, you’ll need to say what that was. But the fundamental issue is that artist is not a defined symbol at global scope, which is where you’re trying to use it.

If you have artist defined in some non-global location (good! globals are a bad thing), then you’ll want to hook up your event handler via modern techniques rather than using the onXyz attributes.

The simplest way if you’re not using a DOM library (like jQuery or similar) is to assign to the onXyz property of the select box element:

(function() { // Something to keep the stuff inside from being globals
    var artist = "Joe Cocker";

    var selectBox = document.querySelector("selector for the select box");
    selectBox.onchange = function() {
        loadDates(artist); // `artist` is in scope now
    };
})();

In general, though, I avoid the onXyz properties because they only allow a single handler per event per element, preferring the DOM method addEventListener (and its Microsoft-specific predecessor, attachEvent). I didn’t use them above for simplicity. If you don’t use a DOM library, you might want this hookEvent function given in another answer which uses addEventListener if it’s there, or attachEvent if it isn’t, and supplies some missing bits for the attachEvent browsers.

3

solved Javascript can’t pass parameters between functions