0

I'm trying to create a simple js script that populates dynamically 2 drop downs but i don't understand what am i doing wrong with my script:(

<head>
    <script>
        var carModels = {
            Audi : ["A3", "A4" ],
            Alfa-Romeo : ["Giullietta", "Giullia" ]
        }

        function makeSubmenu(value) {
            if (value.length == 0){
                document.getElementById("modelId").innerHTML = "<option></option>";
            } else {
                var modelOptions = "";
                for (modelCar in carModels[value]) {
                    modelOptions += "<option>" + carModels[value][modelCar]
                            + "</option>";
                }
                document.getElementById("modelId").innerHTML = modelOptions;
            }
        }

        function resetSelection() {
            document.getElementById("marcaId").selectedIndex = 0;
            document.getElementById("modelId").selectedIndex = 0;
        }
    </script>
</head>
<body onload="resetSelection()">
<div align="center">
    <form th:action="@{/search}" method="POST">

        <select id="marcaId" size="1" name="marca" required onchange="makeSubmenu(this.value)">
            <option></option>
            <option>Audi</option>
            <option>Alfa-Romeo</option>
        </select>

        <select id="modelId" size="1" name="model" required >
            <option></option>
        </select>

        <input type="submit" value="Search">
    </form>
 </body>

I get those 2 errors:

Uncaught ReferenceError: resetSelection is not defined
    at onload ((index):6)
Uncaught ReferenceError: makeSubmenu is not defined
    at HTMLSelectElement.onchange ((index):13)
onchange @ (index):13

I don't understand why it says that those methods are not defined

Tr Sorin
  • 125
  • 9

1 Answers1

2

You need to wrap the property Alfa-Romeo in quotes, like this ..

var carModels = {
    Audi : ["A3", "A4" ],
    "Alfa-Romeo" : ["Giullietta", "Giullia" ]
}

Please refer this answer for the reasoning.

The only reasons to quote object-keys are

  • the property name is reserved/used by the browser/js engine (eg. "class" in IE)
  • you have special characters or white spaces in your key
rmn
  • 1,119
  • 7
  • 18