0
我試圖做一個動態從屬下拉選擇菜單與國家,州和城市只有jquery/javascrip和HTML,但是當選擇國家直接選擇的城市和我已經看到了很多的教程,問題是,我不希望使用的數據庫,我想直接創建對象,如果有人可以幫助我,這裏是我的代碼:動態依賴的下拉菜單沒有數據庫的Jquery
$(document).ready(function(){
var countries = {
'mexico': [{
display: "Ciudad de Mexico",
value: "mx-city"
}, {
display: "Jalisco",
value: "jalisco"
}],
'usa': [{
display: "Texas",
value: "texas"
}, {
display: "Ohio",
value: "ohio"
}],
'canada': [{
display: "Montreal",
value: "montreal"
}, {
display: "Toronto",
value: "toronto"
}]
};
var states = {
'mx-city': [{
display: "Benito Juarez",
value: "benito-juarez"
}, {
display: "Cuauhtemoc",
value: "cuauhtemoc"
}],
'jalisco': [{
display: "Zapopan",
value: "zapopan"
}, {
display: "Guadalajara",
value: "Guadalajara"
}],
'texas': [{
display: "San Antonio",
value: "san-antonio"
}, {
display: "Austin",
value: "austin"
}],
'ohio': [{
display: "Colombus",
value: "colombus"
}, {
display: "Cleveland",
value: "cleveland"
}],
'montreal': [{
display: "Quebec",
value: "Quebec"
}, {
display: "Vermont",
value: "vermont"
}],
'toronto': [{
display: "Ontario",
value: "ontario"
}, {
display: "York",
value: "york"
}]
};
$("#parent_selection").change(function() {
var parent = $(this).val();
if (countries[parent] == undefined) {
return $("#child_selection").html('Selecciona tu Estado');
}
list(countries[parent]);
});
function list(array_list){
$("#child_selection").html("");
$(array_list).each(function (i) {
$("#child_selection").append('<option value="'+array_list[i].value+'">'+array_list[i].display+"</option>");
});
}
$('#child_selection').change(function() {
var state = $(this).val();
if (states[state] == undefined) {
return $("#child").text('Selecciona tu ciudad');
}
list(states[state]);
});
function list(array_list){
$("#child").html("");
$(array_list).each(function (i) {
$("#child").append('<option value="'+array_list[i].value+'">'+array_list[i].display+"</option>");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="" enctype="application/json">
<br/>Nombre: <input type="text" />
<br/>Edad: <input type="text" />
<br/>Pais:
<select name="parent_selection" id="parent_selection">
<option value="">Selecciona tu pais</option>
<option value="mexico">Mexico</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
</select>
<br />Estado:
<select name="child_selection" id="child_selection">
<option value="">Selecciona tu estado</option>
</select>
<br/>Ciudad:
<select name="child" id="child">
<option value="">Selecciona tu ciudad</option>
</select>
<input type="submit" value="Submit" />
</form>
嗨!喬爾!非常感謝你的幫助,現在的問題是,例如,選擇墨西哥後,它會加載州和州的城市,但正如你所說,我會嘗試與Ayax合作,如果你知道的話一個教程做它將不勝感激!再次感謝你:) –
[Exemple codepen](http://codepen.io/SirXplosiv/pen/GWrNMB)funciona tal y como esperabas sino me equivoco,我的意思是,當你選擇一個國家時,加載狀態下拉菜單,然後選擇一個狀態,自動加載城市 –