[jQuery] Refactoring help

[jQuery] Refactoring help


Hey guys!
I've spent a bit of time writing some JS to pull some JSON into three
dropdowns, and the resulting code is a bit messy (70 lines, of which,
40 is just repetition).
I'm a bit useless with refactoring, and I would really appreciate some
pointers in trying to tidy this code up. I'm not normally asking for
help, but JS refactoring is definitely my Achilles heel! Moving some
of this into functions is probably my best bet, but I'm not sure where
to do that.
Thanks in advance!
[code]
var jsonReq;
$(function() {
$("#secondLoc").attr("disabled","disabled");
$("#thirdLoc").attr("disabled","disabled");
$.getJSON("locationtree.json",function(data){
jsonReq = data;
$.each(data.LocationTree.Location, function(i,item){
$("#topLoc").append("<optgroup label=\""+item.Name+"\">");
$.each(item.Location, function(j,topLoc){
$("#topLoc").append("<option value=\""+topLoc.Code
+"\">"+topLoc.Name+"</option>");
$("#secondLoc").append("<option value=\"\">Choose an optional
region</option>");
if(topLoc.Location != null) {
$.each(topLoc.Location,function(k,secondLoc){
$("#secondLoc").attr("disabled","");
$("#secondLoc").append("<option value=\""+secondLoc.Code
+"\">"+secondLoc.Name+"</option>");
});
}
});
$("#topLoc").append("</optgroup>");
$("#thirdLoc").append("<option value=\"\">No optional location
choices</option>");
$("#secondLoc").append("<option value=\"\">Choose an optional
region</option>");
});
});
$("#topLoc").change(function(){
$("#secondLoc").attr("disabled","disabled");
$("#thirdLoc").attr("disabled","disabled");
$.each(jsonReq.LocationTree.Location, function(i,item){
$.each(item.Location, function(j,topLoc){
if(topLoc.Code == $("#topLoc").val()) {
$("#secondLoc").empty();
$("#thirdLoc").empty();
$("#secondLoc").append("<option value=\"\">Choose an
optional region</option>");
$("#thirdLoc").append("<option value=\"\">Choose an optional
location</option>");
if(topLoc.Location != null) {
$.each(topLoc.Location,function(k,secondLoc){
$("#secondLoc").attr("disabled","");
$("#secondLoc").append("<option value=\""+secondLoc.Code
+"\">"+secondLoc.Name+"</option>");
});
}
}
});
});
});
$("#secondLoc").change(function(){
$("#thirdLoc").attr("disabled","disabled");
$.each(jsonReq.LocationTree.Location, function(i,item){
$.each(item.Location, function(j,topLoc){
if(topLoc.Code == $("#topLoc").val()) {
$.each(topLoc.Location,function(k,secondLoc){
if(secondLoc.Code == $("#secondLoc").val()) {
$("#thirdLoc").empty();
$("#thirdLoc").append("<option value=\"\">Choose an
optional location</option>");
if(secondLoc.Location != null) {
$.each(secondLoc.Location,function(l,thirdLoc){
$("#thirdLoc").append("<option value=
\""+thirdLoc.Code+"\">"+thirdLoc.Name+"</option>");
$("#thirdLoc").attr("disabled","");
});
}
}
});
}
});
});
});
});
[/code]