Skip to content

Instantly share code, notes, and snippets.

@codeprimate
Created July 24, 2012 15:59
Show Gist options
  • Save codeprimate/3170855 to your computer and use it in GitHub Desktop.
Save codeprimate/3170855 to your computer and use it in GitHub Desktop.
var CategoryPicker = function(category_picker_path, subcategory_picker_path) {
this.init = function(){
var obj = this;
var category_picker = $(category_picker_path);
var subcategory_picker = $(subcategory_picker_path);
category_picker.change(function(){
if (this.value != '') {
var target_url = "/category_groups/" + this.value + "/subcategories.json";
$.ajax( target_url, {
context: document.body,
datatype: 'json',
success: function(data){
obj.setSubcategoryOptions(data, subcategory_picker)
}
})
} else {
obj.clearOptions(subcategory_picker)
}
})
// Manually fire the change event to ensure options are correct
category_picker.change()
}
this.clearOptions = function(target){
target.attr('disabled', 'disabled');
for((x=(target[0].options.length - 1)); x >= 0; x-- ) {
target[0].options[x] = null
}
target.attr('disabled',null)
}
this.setSubcategoryOptions = function(data, target) {
// Remember the value of the subcategory selection
var subcat_selection = target[0].value;
this.clearOptions(target);
target.attr('disabled','disabled');
target.append("<option value=''>--Please Select --</option>");
for(x=0; x < data.length; x++) {
target.append("<option value='" + data[x][0] + "'>" + data[x][1]+ "</option>")
}
// Select the option that matches the option selected before
// the option list was refreshed
for(i=0;i<target[0].options.length; i++) {
if (target[0].options[i].value == subcat_selection) {
target[0].selectedIndex = i;
break;
}
}
target.attr('disabled',null)
}
}
<script type="text/javascript">
$(function(){
var i = new CategoryPicker();
i.init()
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment