簡體   English   中英

如何將一個下拉菜單中選擇的選項的屬性添加到另一個下拉菜單?

[英]How to add a property of an option selected in one dropdown menu to another dropdown menu?

我想從第一個下拉菜單中將所選選項的俱樂部列表添加到第二個下拉菜單中。 例如,如果用戶在第一個下拉菜單中選擇國家/地區時選擇了“英格蘭”,則第二個下拉菜單的選項應為englandclubs的所有元素(england對象的clubs屬性),其中每個元素該陣列是一個選項(例如,阿森納足球俱樂部,阿斯頓維拉足球俱樂部,...,西漢姆聯足球俱樂部)。

不幸的是,第二個下拉菜單根本沒有顯示我要顯示的選項,並且該問題顯示在下面的屏幕截圖中

問題的屏幕截圖

如何將所選國家/地區的所有俱樂部作為選項添加到第二個下拉菜單中?

問題正在發生在下面的代碼中:

// 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>");
});

您需要通過事件委托將countries onchange事件綁定到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 FC', 'Aston Villa FC', 'Burnley FC', 'Chelsea FC', 'Crystal Palace FC', 'Everton FC', 'Hull City AFC', 'Leicester City FC', 'Liverpool FC', 'Manchester City FC', 'Manchester United FC', 'Newcastle United FC', 'Queens Park Rangers FC', 'Southampton FC', 'Stoke City FC', 'Sunderland AFC', 'Swansea City AFC', 'Tottenham Hotspur FC', 'West Bromwich Albion FC', 'West Ham United FC']; var franceclubs = ['SC Bastia', 'FC Girondins de Bordeaux', 'Stade Malherbe Caen', 'Évian Thonon Gaillard FC', '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 FC', 'Stade de Reims', 'Stade Rennais FC', '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 BC', 'Cagliari Calcio', 'AC Cesena', 'AC Chievo Verona', 'Empoli FC', 'ACF Fiorentina', 'Genoa CFC', 'FC Internazionale Milano', 'Juventus FC', 'SS Lazio', 'AC Milan', 'SSC Napoli', 'US Città di Palermo', 'Parma FC', 'AS Roma', 'UC Sampdoria', 'US Sassuolo Calcio', 'Torino FC', 'Udinese Calcio', 'Hellas Verona FC']; 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 CF', '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> 

您可以通過最簡單的方法進行操作:

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"));
             }
         }
    });
});

}));

好吧,這是您的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;
      }
});

添加以下內容:

$('#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));
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM