stefanbc
5/9/2013 - 7:30 PM

Change select box options dynamically

Change select box options dynamically

// Change select box options based on value from another select box

$(document).ready(function(){
  
  // If the user select a value from the select
  $('#FIRST_SELECT').change(function(){
        
        // Get the selected value
        var get_eveniment = $(this).val();

        // If the value is equal to something do stuff
        if (get_eveniment == "FIRST_VALUE") {
            
            // The values stored in an array
            selectValues = { "OPTION_1" : "VALUE_1", "OPTION_2" : "VALUE_2" };
            
            // If the select has other options we clear those out
            $("#SECOND_SELECT").find('option').remove();
            
            // Append each value from the array to the second select as options
            $.each(selectValues, function(key, value) {
                $('#SECOND_SELECT').append($("<option/>", {
                    value: key,
                    text: value
                }));
            });
        
        // If the value is equal to another something do stuff
        } else if (get_eveniment == "SECOND_VALUE") {
            
            // The values stored in an array
            selectValues = { "OPTION_3" : "VALUE_3", "OPTION_4" : "VALUE_4" };
            
            // If the select has other options we clear those out
            $("#SECOND_SELECT").find('option').remove();
            
            // Append each value from the array to the second select as options
            $.each(selectValues, function(key, value) {
                $('#SECOND_SELECT').append($("<option/>", {
                    value: key,
                    text: value
                }));
            });
        
        // If the value is equal to nothing empty the select
        } else if (!get_eveniment) {
            
            // If the select has other options we clear those out
            $("#SECOND_SELECT").find('option').remove();

        }
    });
    
});

// Done!