【问题标题】:How to add a property of an option selected in one dropdown menu to another dropdown menu?如何将一个下拉菜单中选择的选项的属性添加到另一个下拉菜单?
【发布时间】:2015-05-04 13:08:05
【问题描述】:

我想将第一个下拉菜单中所选选项的俱乐部列表添加到我的第二个下拉菜单中。例如,如果用户在第一个下拉菜单中选择国家时选择“英格兰”,那么第二个下拉菜单的选项应该是 englandclubs 的所有元素(england 对象的 clubs 属性) - 其中每个元素该数组中的一个是一个选项(即阿森纳 F.C.、阿斯顿维拉 F.C.、...、西汉姆联 F.C.)。

不幸的是,第二个下拉菜单根本没有显示我想要显示的选项,问题出现在下面的屏幕截图中

如何将所选国家的所有俱乐部作为选项附加到第二个下拉菜单中?

问题出在下面的代码中:

// clubs of 5 countries 
var englandclubs = ['Arsenal F.C.', 'Aston Villa F.C.', 'Burnley F.C.', 'Chelsea F.C.', 'Crystal Palace F.C.', 'Everton F.C.', 'Hull City A.F.C.', 'Leicester City F.C.', 'Liverpool F.C.', 'Manchester City F.C.', 'Manchester United F.C.', 'Newcastle United F.C.', 'Queens Park Rangers F.C.', 'Southampton F.C.', 'Stoke City F.C.', 'Sunderland A.F.C.', 'Swansea City A.F.C.', 'Tottenham Hotspur F.C.', 'West Bromwich Albion F.C.', 'West Ham United F.C.'];

var franceclubs = ['SC Bastia', 'FC Girondins de Bordeaux', 'Stade Malherbe Caen', 'Évian Thonon Gaillard F.C.', 'En Avant de Guingamp', 'RC Lens', 'Lille OSC', 'FC Lorient', 'Olympique Lyonnais', 'Olympique de Marseille', 'FC Metz','AS Monaco FC', 'Montpellier HSC', 'FC Nantes', 'OGC Nice', 'Paris Saint-Germain F.C.', 'Stade de Reims', 'Stade Rennais F.C.', 'AS Saint-Étienne', 'Toulouse FC'];

var germanyclubs = ['FC Augsburg', 'Bayer 04 Leverkusen', 'FC Bayern München', 'Borussia Dortmund', 'Borussia Mönchengladbach', 'Eintracht Frankfurt', 'SC Freiburg', 'Hamburger SV', 'Hannover 96', 'Hertha BSC', 'TSG 1899 Hoffenheim', '1. FC Köln', '1. FSV Mainz 05', 'SC Paderborn 07', 'FC Schalke 04', 'VfB Stuttgart', 'SV Werder Bremen', 'VfL Wolfsburg'];

var italyclubs = ['Atalanta B.C.', 'Cagliari Calcio', 'A.C. Cesena', 'A.C. Chievo Verona', 'Empoli F.C.', 'ACF Fiorentina', 'Genoa C.F.C.', 'F.C. Internazionale Milano', 'Juventus F.C.', 'S.S. Lazio', 'A.C. Milan', 'S.S.C. Napoli', 'U.S. Città di Palermo', 'Parma F.C.', 'A.S. Roma', 'U.C. Sampdoria', 'U.S. Sassuolo Calcio', 'Torino F.C.', 'Udinese Calcio', 'Hellas Verona F.C.'];

var spainclubs = ['UD Almería', 'Athletic Bilbao', 'Atlético Madrid', 'FC Barcelona', 'Celta de Vigo', 'Córdoba CF', 'Deportivo de La Coruña', 'SD Eibar', 'Elche CF', 'RCD Espanyol', 'Getafe CF', 'Granada CF', 'Levante UD', 'Málaga CF', 'Rayo Vallecano', 'Real Madrid C.F.', 'Real Sociedad', 'Sevilla FC', 'Valencia CF', 'Villarreal CF'];

// countries in UEFA
var countries = [{name: "England", clubs: englandclubs},
                 {name: "France", clubs: franceclubs},
                 {name: "Germany", clubs: germanyclubs},
                 {name: "Italy", clubs: italyclubs},
                 {name: "Spain", clubs: spainclubs}];

$(function() {

    $(".formArea").append("<form name='clubinsertion' action='#' method='post' id='clubinsertion'>" +
                          "</form>");
    $("#clubinsertion").append("<label>Country:</label>" +
                               "<br>" +
                               "<select name='countries' id='countries'>" +
                               "<option disabled selected> -- Choose a country -- </option>" +
                               "</select>" +
                               "<br>");

    // adds the name of each country to the dropdown menu
    var countrymenu = $('#countries');

    $.each(countries, function(val, obj) {
        countrymenu.append($('<option></option>').val(val).html(obj.name));
    });

    $("#clubinsertion").append("<label>Club:</label>" +
                               "<br>" +
                               "<select name='clubs' id='clubs'>" +
                               "</select>" +
                               "<br>");

    // gets the selected option from the countries dropdown menu
    var selectedcountry = $('#countries option:selected').text()

    // adds each club of selected country into the clubs dropdown menu
    var clubmenu = $('#clubs');

    for (var i = 0; i < countries.length; i++) {
        if (selectedcountry === countries[i].name) {
            $.each(countries, function(val, obj) {
                clubmenu.append($('<option></option>').val(val).html(obj.clubs));
            });
        }
    }


    // submit button for the form
    $("#clubinsertion").append("<button type='submit'>Enter Club</button>");
});

【问题讨论】:

  • 您还没有为您的select 选项编写onchange 事件吗?请尝试添加一些html!

标签: javascript jquery html drop-down-menu


【解决方案1】:

您需要在countries 下拉菜单上绑定onchange 事件,例如,

$('.formArea').on('change','#countries',function(){
      var selectedcountry = $('#countries option:selected').text();
      setClubsData(selectedcountry);
});

function setClubsData(selectedcountry){
    // adds each club of selected country into the clubs dropdown menu
    var clubmenu = $('#clubs').html('');// make it blank before append

    for (var i = 0; i < countries.length; i++) {
        if (selectedcountry === countries[i].name) {
            // loop for countries[i].clubs not for countries
            $.each(countries[i].clubs, function(key, val) {
                // simply get the value from clup array and append it
                clubmenu.append($('<option></option>').val(val).html(val));
            });
        }
    }
}

// clubs of 5 countries 
var englandclubs = ['Arsenal F.C.', 'Aston Villa F.C.', 'Burnley F.C.', 'Chelsea F.C.', 'Crystal Palace F.C.', 'Everton F.C.', 'Hull City A.F.C.', 'Leicester City F.C.', 'Liverpool F.C.', 'Manchester City F.C.', 'Manchester United F.C.', 'Newcastle United F.C.', 'Queens Park Rangers F.C.', 'Southampton F.C.', 'Stoke City F.C.', 'Sunderland A.F.C.', 'Swansea City A.F.C.', 'Tottenham Hotspur F.C.', 'West Bromwich Albion F.C.', 'West Ham United F.C.'];

var franceclubs = ['SC Bastia', 'FC Girondins de Bordeaux', 'Stade Malherbe Caen', 'Évian Thonon Gaillard F.C.', 'En Avant de Guingamp', 'RC Lens', 'Lille OSC', 'FC Lorient', 'Olympique Lyonnais', 'Olympique de Marseille', 'FC Metz', 'AS Monaco FC', 'Montpellier HSC', 'FC Nantes', 'OGC Nice', 'Paris Saint-Germain F.C.', 'Stade de Reims', 'Stade Rennais F.C.', 'AS Saint-Étienne', 'Toulouse FC'];

var germanyclubs = ['FC Augsburg', 'Bayer 04 Leverkusen', 'FC Bayern München', 'Borussia Dortmund', 'Borussia Mönchengladbach', 'Eintracht Frankfurt', 'SC Freiburg', 'Hamburger SV', 'Hannover 96', 'Hertha BSC', 'TSG 1899 Hoffenheim', '1. FC Köln', '1. FSV Mainz 05', 'SC Paderborn 07', 'FC Schalke 04', 'VfB Stuttgart', 'SV Werder Bremen', 'VfL Wolfsburg'];

var italyclubs = ['Atalanta B.C.', 'Cagliari Calcio', 'A.C. Cesena', 'A.C. Chievo Verona', 'Empoli F.C.', 'ACF Fiorentina', 'Genoa C.F.C.', 'F.C. Internazionale Milano', 'Juventus F.C.', 'S.S. Lazio', 'A.C. Milan', 'S.S.C. Napoli', 'U.S. Città di Palermo', 'Parma F.C.', 'A.S. Roma', 'U.C. Sampdoria', 'U.S. Sassuolo Calcio', 'Torino F.C.', 'Udinese Calcio', 'Hellas Verona F.C.'];

var spainclubs = ['UD Almería', 'Athletic Bilbao', 'Atlético Madrid', 'FC Barcelona', 'Celta de Vigo', 'Córdoba CF', 'Deportivo de La Coruña', 'SD Eibar', 'Elche CF', 'RCD Espanyol', 'Getafe CF', 'Granada CF', 'Levante UD', 'Málaga CF', 'Rayo Vallecano', 'Real Madrid C.F.', 'Real Sociedad', 'Sevilla FC', 'Valencia CF', 'Villarreal CF'];

// countries in UEFA
var countries = [{
  name: "England",
  clubs: englandclubs
}, {
  name: "France",
  clubs: franceclubs
}, {
  name: "Germany",
  clubs: germanyclubs
}, {
  name: "Italy",
  clubs: italyclubs
}, {
  name: "Spain",
  clubs: spainclubs
}];

$(function() {

  $('.formArea').on('change', '#countries', function() {
    var selectedcountry = $('#countries option:selected').text();
    setClubsData(selectedcountry);
  });

  function setClubsData(selectedcountry) {
    // adds each club of selected country into the clubs dropdown menu
    var clubmenu = $('#clubs').html(''); // make it blank before append

    for (var i = 0; i < countries.length; i++) {
      if (selectedcountry === countries[i].name) {
        // loop for countries[i].clubs not for countries
        $.each(countries[i].clubs, function(key, val) {
          // simply get the value from clup array and append it
          clubmenu.append($('<option></option>').val(val).html(val));
        });
      }
    }
  }

  $(".formArea").append("<form name='clubinsertion' action='#' method='post' id='clubinsertion'>" +
    "</form>");
  $("#clubinsertion").append("<label>Country:</label>" +
    "<br>" +
    "<select name='countries' id='countries'>" +
    "<option disabled selected> -- Choose a country -- </option>" +
    "</select>" +
    "<br>");

  // adds the name of each country to the dropdown menu
  var countrymenu = $('#countries');

  $.each(countries, function(val, obj) {
    countrymenu.append($('<option></option>').val(val).html(obj.name));
  });

  $("#clubinsertion").append("<label>Club:</label>" +
    "<br>" +
    "<select name='clubs' id='clubs'>" +
    "</select>" +
    "<br>");

  // gets the selected option from the countries dropdown menu
  var selectedcountry = $('#countries option:selected').text();
  setClubsData(selectedcountry);
  // adds each club of selected country into the clubs dropdown menu
  /*var clubmenu = $('#clubs');

  for (var i = 0; i < countries.length; i++) {
    if (selectedcountry === countries[i].name) {
      $.each(countries, function(val, obj) {
        clubmenu.append($('<option></option>').val(val).html(obj.clubs));
      });
    }
  }*/


  // submit button for the form
  $("#clubinsertion").append("<button type='submit'>Enter Club</button>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="formArea">
  <div>

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      你可以用最简单的方法来做:

      1 - 为有选项的国家添加下拉列表(选项值为国家名称)。

      2 - 试试这个代码:

      $(document).ready(function(){
          $("#country_dropdown").on('change',function(){
               var country_name = $(this).val();
               for(var k in countries){
                   if(contries[k].name==country_name){
                      //it's country which selected by user
                      var club_dropdown=$('<div/>',{
                          id:'club_dropdown'
                      });
                      for(var s in countries[k].clubs){
                          club_dropdown.append('<option value="'+countries[k].clubs[s]+'">'+countries[k].clubs[s]+'"</option>"');
                      }
                      club_dropdown.appendTo($(".formArea"));
                   }
               }
          });
      });
      
      }));
      

      【讨论】:

        【解决方案4】:

        这就是你的change 函数的样子,在此之前我想向你展示DEMO

        $('#countries').on('change',function(){
            var country=$(this).find(":selected").text();
            $('#clubs').find('option').remove();
            switch(country)
            {
                case 'England':
                    $.each(englandclubs, function(key, value) {   
                            $('#clubs')
                            .append($("<option></option>")
                            .text(value)); 
                    });
                    break;
                case 'France':
                    $.each(franceclubs, function(key, value) {   
                            $('#clubs')
                            .append($("<option></option>")
                            .text(value));  
                    });
                case 'Germany':
                    $.each(germanyclubs, function(key, value) {   
                            $('#clubs')
                            .append($("<option></option>")
                            .text(value)); 
                    });
                    break;
                case 'Italy':
                    $.each(italyclubs, function(key, value) {   
                            $('#clubs')
                            .append($("<option></option>")
                            .text(value)); 
                    });
                    break;
                case 'Spain':
                    $.each(spainclubs, function(key, value) {   
                            $('#clubs')
                            .append($("<option></option>")
                            .text(value)); 
                    });
                    break;
              }
        });
        

        【讨论】:

        • 非常感谢您的帮助。我缩短了您的解决方案,以便它使用 for 循环和 if 语句而不是 switch 语句,因为我计划使用 54 个国家而不是 5 个国家和 switch 语句将占用大量代码行。抱歉,如果我没有在解决方案中添加 HTML 代码,因为我使用 Jade 作为 HTML 的标记语言,因为这是使用 Node.js 编写的 Web 应用程序。
        • @ArchitMahto。伟大的!快乐编码.. :)
        【解决方案5】:

        添加以下内容:

        $('#countries').on('change', function (e) {
            var clubmenu = $('#clubs');
            var optionSelected = $("option:selected", this);
        
            var clubsArray = countries[this.value].clubs;
            $.each(clubsArray, function(ind, val) {
                clubmenu.append($('<option></option>').val(ind).html(val));
            });
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-01-10
          • 1970-01-01
          • 2017-04-30
          • 2019-07-26
          • 1970-01-01
          • 2022-11-17
          • 1970-01-01
          相关资源
          最近更新 更多