Monday, March 9, 2009

Cascaded HTML SELECT elements using JQuery V2

This is a small update i made to the code, This code fixes a bug detected and also get rid of some duplicated code

his is an update to the JS function

eSpace.HTML = {
cascadeLists: function(parentId, childId, callbackFunction){
$("body").append('');
var childOptions = $('#' + childId + ' option');
$('#' + parentId + childId).html(childOptions);

$('#' + parentId).change(function(){
var parent = $('#' + parentId)[0];

var selectedOptionValue = '';
if (parent.selectedIndex > -1)
selectedOptionValue = parent.options[parent.selectedIndex].value;

if (selectedOptionValue == '')
$('#' + childId).html($('#' + parentId + childId + ' option[value=""]').clone());
else {
var childs = $('#' + parentId + childId + ' option[parent="'+selectedOptionValue+'"]');
if(childs.size() == 0)
$('#' + childId).html($('#' + parentId + childId + ' option[value=""]').clone());
else
$('#' + childId).html($('#' + parentId + childId + ' option[parent="' + selectedOptionValue + '"]').clone());
}

$('#' + childId).trigger("change");

if(callbackFunction != null) callbackFunction(parent.options[parent.selectedIndex]);
});

$('#' + parentId).trigger("change");
}
}

No comments: