Home >Web Front-end >JS Tutorial >jquery ajax implements three-level no-refresh linkage of the drop-down box, and saves and maintains the selected value_jquery
Function: three-level linkage of province, city and region, using jquery ajax to obtain data binding, the selected value can be saved and kept selected after page refresh or submission
Put the following code in a separate js file and reference it on the page to call
return cookieValue;
}
//保存cookie值
function writeCookie(name, value, hours, escp) {
var expire = "";
if (hours != null) {
expire = new Date((new Date()).getTime() + hours * 3600000);
expire = "; expires=" + expire.toGMTString();
}
if (escp == "True") {
document.cookie = name + "=" + value + expire;
} else {
document.cookie = name + "=" + escape(value) + expire;
}
}
//省市区,流域,水系,断面条件选择
$(function() {
var $ddlprovince = $("#ddlProvince"); //省份
var $ddlcity = $("#ddlCity"); //城市
var $ddlarea = $("#ddlAreaName"); //区域
//根据省份查询城市
//$ddlprovince.focus(); //不要加focus,否则设置selected有问题
$ddlprovince.bind("change keyup", function() {
if ($(this).val() != "-1") {
loadWater($(this).val(), "SelectCity");
} else {
$("select[id$=ddlCity] > option").remove();
$ddlcity.append($("").val("-1").html("--请选择--"));
}
//从新选择省份或者从新选择城市都会初始化区域
$("select[id$=ddlAreaName] > option").remove();
$ddlarea.append($("").val("-1").html("--请选择--"));
});
//如果城市没有填充数据,省份有选择数据则加载数据
if ($("select[id$=ddlCity] > option").length == 1 && $ddlprovince.val() != "-1") {
loadWater($ddlprovince.val(), "SelectCity");
//读cookie,有值则设为选中状态
var cityname = readCookie("JQ_CityName");
if (cityname != null && cityname != "undefined" && cityname != "") {
//$("select[id=ddlWaterXiName] > option:contains('" + watername + "')").attr("selected", "true");
$("select[id$=ddlCity] > option[value='" + cityname + "']").attr("selected", "true");
}
}
//Query area based on city
//$ddlcity.focus();
$ddlcity.bind("change keyup", function() {
if ($(this).val( ) != "-1") {
.val(), 0.5, true);
} else {
$("select[name$=ddlAreaName] > option").remove(); ").val("-1").html("--Please select--"));
//If the district name has no data filled in and the city has selected data, load the data
if ($("select[id$=ddlAreaName] > option").length == 1 && $ddlcity .val ()! = "-1") {
Loadwater ($ ddlcity.val (), "selectareaname"); readCookie("JQ_AreaName");
$("select[id=ddlAreaName] > option[ value='" areaname "']").attr("selected", "true");
}
}
$ddlarea.bind("change keyup", function() {
if ($(this).val() != "-1") {
//Select the value to save the cookie
}
});
function loadWater(selectedItem, typename) {
$.ajax({
type: "GET",
data: { usetype: typename, id: selectedItem },
contentType: "application/json; charset=utf-8",
async: false,
success: function Success(data) {
bindWater(data, typename);
}
});
}
function bindWater(data, typename) {
if (typename == "SelectCity") { //Bind city
"").val("-1").html("--Please select--"));
for (var i = 0; i < data.length; i ) {
$("select[id$=ddlCity]").append($("