"uncaught Typeerror: Bgcolor Is Not A Function" In Html Select Onchange
I have an HTML switch with an onchange tag that should run the JavaScript function bgColor with the argument this but whenever I try using this, it gives me an error: Uncaught Type
Solution 1:
Use a different name for the function. The environment in which onxyz
-attribute style event handler code is run has several with
clauses (effectively) putting all properties of the element (and some other things) in scope*, with precedence over globals. There's an old, no-longer-standard property called bgColor
on elements which is getting in the way of your global function.
Another name (like setBackgroundColor
) will work:
// The following is for changing graph colorvar graphColor = "blue";
var graphBgColor = "rgba(106, 154, 177, 0.3)";
var graphBorderColor = "rgb(99, 121, 132)";
functionsetBackgroundColor(s) {
graphColor = $(s).val();
graphBgColor = graphColor == "blue" ? "rgba(106, 154, 177, 0.3)" : "rgba(0, 0, 255, 0.3)";
graphBorderColor = graphColor == "blue" ? "rgb(99, 121, 132)" : "rgb(0, 0, 255)";
update_temp_and_time();
}
functionupdate_temp_and_time() {
console.log("graphColor = " + graphColor);
}
<selectid="selectBgColor"onchange="setBackgroundColor(this)"><optionvalue="blue"selected>Blue</option><optionvalue="gray">Gray</option></select><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
* This is one of the many reasons not to use onxyz
-attribute style event handlers, and not to use globals. Instead, ensure your code is not at global scope (for instance, wrap it in a scoping function) and hook up your handlers dynamically.
E.g.:
// Scoping function
(function() {
// The following is for changing graph colorvar graphColor = "blue";
var graphBgColor = "rgba(106, 154, 177, 0.3)";
var graphBorderColor = "rgb(99, 121, 132)";
$("#selectBgColor").on("change", function() {
graphColor = $(this).val();
graphBgColor = graphColor == "blue" ? "rgba(106, 154, 177, 0.3)" : "rgba(0, 0, 255, 0.3)";
graphBorderColor = graphColor == "blue" ? "rgb(99, 121, 132)" : "rgb(0, 0, 255)";
update_temp_and_time();
});
functionupdate_temp_and_time() {
console.log("graphColor = " + graphColor);
}
})();
<selectid="selectBgColor""><optionvalue="blue"selected>Blue</option><optionvalue="gray">Gray</option></select><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Post a Comment for ""uncaught Typeerror: Bgcolor Is Not A Function" In Html Select Onchange"