动态填充下拉

时间:2015-12-30 06:12:37

标签: javascript html html5

我正在寻找一些动态自动填充下拉菜单的帮助。

我写的代码对我来说不起作用,但它最初做了,现在已经停止了。

我哪里错了?

HTML:

<form id="booking_form" onsubmit="return checkForm()" method="post" action="">
    <div>
        <!-- Select Movie -->
        <span class="label">Movie Name:</span>
        <select name="movie" id="movie_name" onChange="changeday(this.value);">
            <option value="" disabled selected>Choose Movie</option>
            <option value="SW">Star Wars: The Force Awakens</option>
            <option value="WC">Wedding Crashers</option>
            <option value="GD">The Good Dinosaur</option>
            <option value="BR">Battle Royale</option>
        </select>
    </div>

    <div>
        <!-- Select Day -->                     
        <span class="label">Session Day:</span>
        <select name="day" id="session_day">
            <option value="" disabled selected>Please Select a Movie</option>
        </select>
    </div>
</form>

JavaScript的:

var moviesByDays = {
        SW: ["Monday", "Monday", "Monday", "Monday"],
        WC: ["Tuesday", "Tues", "Tues", "Tues"],
        GD: ["Wednesday", "Wed", "Wed", "Wed", "Wed"],
        BR: ["Thursday", "Thurs", "Thurs", "Thurs", "Thurs"]
}

function changeday(value) {
    if (value.length == 0) document.getElementById("session_day").innerHTML = "<option></option>";
    else {
        var catOptions = "";
        for (session_dayId in moviesByDay[value]) {
            daysOptions += "<option>" + moviesByDays[value][session_dayId] + "</option>";
        }
        document.getElementById("session_day").innerHTML = daysOptions;
    }
}

我该如何做到这一点?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

那是因为你在变量和赋值中犯了一些错误。请在Script标记中使用以下内容:

  var moviesByDays = {
        SW: ["Monday", "Monday", "Monday", "Monday"],
        WC: ["Tuesday", "Tues", "Tues", "Tues"],
        GD: ["Wednesday", "Wed", "Wed", "Wed", "Wed"],
        BR: ["Thursday", "Thurs", "Thurs", "Thurs", "Thurs"]
  }


  function changeday(value) {
    var daysOptions = []; //That will Clear first selection on every new selection
    if (value.length == 0) document.getElementById("session_day").innerHTML = "<option></option>";
    else {
        var catOptions = "";
        for (session_dayId in moviesByDays[value]) {                
            daysOptions += "<option>" + moviesByDays[value][session_dayId] + "</option>";
        }
        document.getElementById("session_day").innerHTML = daysOptions;
    }
 }

Demo