Mi è piaciuto molto la soluzione @Marko Dunic, ma non ha soddisfatto le mie esigenze per il fissaggio ID alle opzioni. Una volta collegato gli ID, mi sono reso conto che avrei potuto rendere il codice JS ancora più piccolo e semplice. La mia soluzione è progettata per quando i dati provengono da un database relazionale e i dati di input JSON mantengono la struttura relazionale con chiavi primarie/esterne. Ecco i dati JSON:
<html lang="en">
<head>
<title>Populate a select dropdown list with jQuery - WebDev Ingredients</title>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript">
var types = [
{ typeID: 1, name: 'Domestic'},
{ typeID: 2, name: 'Import'},
{ typeID: 3, name: 'Boat'}
]
var makes = [
{ typeID: 1, makeID: 1, name: 'Chevy'},
{ typeID: 1, makeID: 2, name: 'Ford'},
{ typeID: 1, makeID: 3, name: 'Delorean'},
{ typeID: 2, makeID: 4, name: 'Honda'},
{ typeID: 2, makeID: 5, name: 'Toyota'},
{ typeID: 2, makeID: 6, name: 'Saab'}
]
var model = [
{ makeID: 1, modelID: 1, name: 'Camaro'},
{ makeID: 1, modelID: 2, name: 'Chevelle'},
{ makeID: 1, modelID: 3, name: 'Nova'},
{ makeID: 2, modelID: 4, name: 'Focus'},
{ makeID: 2, modelID: 5, name: 'Galaxie'},
{ makeID: 2, modelID: 6, name: 'Mustang'},
{ makeID: 4, modelID: 7, name: 'Accord'},
{ makeID: 4, modelID: 8, name: 'Civic'},
{ makeID: 4, modelID: 9, name: 'Odyssey'},
{ makeID: 5, modelID: 10, name: 'Camry'},
{ makeID: 5, modelID: 11, name: 'Corolla'}
]
//
// Put this in a stand alone .js file
//
// returns array of elements whose 'prop' property is 'value'
function filterByProperty(arr, prop, value) {
return $.grep(arr, function (item) { return item[prop] == value });
}
// populates select list from array of items given as objects: { name: 'text', value: 'value' }
function populateSelect(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('please select', '');
$.each(items, function() {
el.options[el.options.length] = new Option(this.name, this.value);
});
}
// initialization
$(document).ready(function() {
// populating 1st select list
populateSelect($('#sType').get(0), $.map(types, function(type) { return { name: type.name, value: type.typeID} }));
// populating 2nd select list
$('#sType').bind('change', function() {
var theModels = filterByProperty(makes, 'typeID', this.value);
populateSelect($('#sMake').get(0), $.map(theModels, function(make) { return { name: make.name, value: make.makeID} }));
$('#sMake').trigger('change');
});
// populating 3nd select list
$('#sMake').bind('change', function() {
var theSeries = filterByProperty(model, 'makeID', this.value);
populateSelect($('#sModel').get(0), $.map(theSeries, function(model) { return { name: model.name, value: model.modelID} }));
});
});
</script>
</head>
<body>
Enter values, click submit, and look at the post parameters
<form method="get" action="index.php">
<div id="selection">
<select id="sType" name="type_id" style="{width=75px}"></select>
<select id="sMake" name="make_id" style="{width=75px}"></select>
<select id="sModel" name="model_id" style="{width=75px}"></select>
</div>
<input type="submit">
</form>
</body>
</html>
Si noti che la mia soluzione sposta la funzionalità in modo che Make-modello sono il 2 ° e 3 ° caselle di testo, e il tipo (interno, l'importazione, barca, ecc) sono il 1 ° livello.Ho ottenuto il boilerplate JS a 23 righe (meno commenti) pur mantenendo una buona formattazione.
I dati JSON sono molto facili da eseguire da query SQL, che vengono memorizzate nella cache in java Lists su init perché il Type-Make-Model raramente cambia. Non uso alcun AJAX dinamico perché questo complica l'architettura e ho una lista relativamente piccola di valori disponibili, quindi la invio alla richiesta della pagina.
"Soluzioni dovrebbe essere una semplice possibile, ma non più semplice" - A. Einstein
grazie per l'impegno che mettete nel vostro risposta. Ho provato il tuo codice e ha funzionato, ma non ho il tempo adesso per imparare esattamente come funziona ... ci tornerò più tardi .. ma sto usando la struttura dell'array ... e ora penso di capire come creare questi array. Grazie ancora –
La struttura dati è in realtà un oggetto Javascript. Puoi trovare qui un discreto tutorial JSON: http://www.hunlock.com/blogs/Mastering_JSON_%28_JavaScript_Object_Notation_%29 – BalusC
L'utilizzo di $ .grep e $ .map per questo è solo il colpo dei maestri. Soluzione fantastica, l'ho usato come base per qualcosa di simile e mi sento come un programmatore migliore per questo. Soluzione eccezionale. – hendrixski