2013-05-23 9 views
5

Sono nuovo allo script Java. Qui ho un esempio di lavoro per 2 drop down Fiddle.3 menu a discesa Popolare in base alla selezione in un altro [menu a cascata]

HTML:

<select id=a></select> 
<select id=b></select> 
<select id=c></select> 

JavaScript:

var data = [ // The data 
    ['ten', [ 
     'eleven','twelve' 
    ]], 
    ['twenty', [ 
     'twentyone', 'twentytwo' 
    ]] 
]; 

$a = $('#a'); // The dropdowns 
$b = $('#b'); 

for(var i = 0; i < data.length; i++) { 
    var first = data[i][0]; 
    $a.append($("<option>"). // Add options 
     attr("value",first). 
     data("sel", i). 
     text(first)); 
} 

$a.change(function() { 
    var index = $(this).children('option:selected').data('sel'); 
    var second = data[index][2]; // The second-choice data 

    $b.html(''); // Clear existing options in second dropdown 

    for(var j = 0; j < second.length; j++) { 
     $b.append($("<option>"). // Add options 
      attr("value",second[j]). 
      data("sel", j). 
      text(second[j])); 
    } 
}).change(); // Trigger once to add options at load of first choice 

Fatemi sapere come aggiungere una goccia nel presente codice.

Grazie

+0

Raka può spiegare il problema po 'di più – vinothini

+0

HI, attualmente sto usando sopra il codice per "Country" e " Stato "Abbassa. il menu a discesa dello stato aggiornerà la selezione del paese in base. ora ho bisogno di aggiungere il campo della città da aggiornare in base alla selezione dello stato. – Raka

risposta

2

provare qualcosa di simile .. ho dovuto cambiare un po 'la struttura dell'oggetto data. Avanti per ottenere il valore della discesa si può solo fare .val()

var data = { 
    'ten': { 
     'eleven': [11, 1111, 111111], 
     'twelve': [12, 1212, 121212] 
    }, 
    'twenty': { 
     'twentyone': [21, 2121, 212121], 
     'twentytwo': [22, 2222, 222222] 
    } 
}, 
$a = $('#a'); // The dropdowns 
$b = $('#b'); 
$c = $('#c'); 

for (var prop in data) { 
    var first = prop; 
    $a.append($("<option>"). // Add options 
    attr("value", first). 
    text(first)); 
} 

$a.change(function() { 
    var firstkey = $(this).val(); 
    $b.html(''); // Clear existing options in second dropdown 
    for (var prop in data[firstkey]) { 
     var second = prop; 
     $b.append($("<option>"). // Add options 
     attr("value", second). 
     text(second)); 
    } 
    $b.change(); 
}).change(); // Trigger once to add options at load of first choice 

$b.change(function() { 
    var firstKey = $a.val(), 
     secondKey = $(this).val(); 
    $c.html(''); // Clear existing options in second dropdown 
    for(var i = 0; i < data[firstKey][secondKey].length; i++) { 
     var third = data[firstKey][secondKey][i] 
     $c.append($("<option>"). // Add options 
     attr("value", third). 
     text(third)); 
    } 
    $c.change(); 
}).change(); 

Check Fiddle

+0

Lavoro esattamente quello che mi aspettavo. Grazie – Raka

+0

@Raka .. Felice di aver aiutato :) –