天天看點

jquery省市縣 三級關聯

$(document).ready(function(){

		getAreaByPid(0,"province");

			 var province = $("#province");
	         var city = $("#city");
	         var county = $("#county");

	       //給省綁定事件,觸發事件後填充市的資料
	       $(province).bind("change keyup", function () {
	             var provinceID = province.attr("value");
	             $(city).find("option").remove();
	             if(provinceID != ''){
		             getAreaByPid(provinceID, "city");
		             city.css("display","block");
		             county.css("display","none");
		         }else{
		        	 city.css("display","none");
		             county.css("display","none");
			      }
	       });

	       //給市綁定事件,觸發事件後填充區的資料
           $(city).bind("change keyup", function () {
               var cityID = city.attr("value");
              $(county).find("option").remove();
               if(cityID != ''){
	               getAreaByPid(cityID, "county");
	               county.css("display","block");
               }else{
            	   county.css("display","none");
                }
           });
           
		});      
function getAreaByPid(pid,nodeid){
			var url = "/manager/config/getAreaByPid" ;
			var param = {
						"pid" : pid,
						"time" : Math.random()
						};
			$.post(url,param,function(data){
				if("province" == nodeid){
					$("#"+nodeid).append("<option  value=''>請選擇省份...</option>");
				}
				if("city" == nodeid){
					$("#"+nodeid).append("<option  value=''>請選擇市/區...</option>");
				}
				if("county" == nodeid){
					$("#"+nodeid).append("<option  value=''>請選擇縣...</option>");
				}
				for(var i=0;i<data.length;i++){
					$("#"+nodeid).append("<option  value='"+data[i].id+"'>"+data[i].name+"</option>");
				}
			});
		}      
<div>
					<select id="province"></select>
					<select id="city" style="display: none;"></select>
					<select id="county" style="display: none;"></select>
				</div>