Skip to content

Instantly share code, notes, and snippets.

@stefanbc
Created May 9, 2013 19:30
Show Gist options
  • Save stefanbc/5549922 to your computer and use it in GitHub Desktop.
Save stefanbc/5549922 to your computer and use it in GitHub Desktop.
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!
@jcsrb
Copy link

jcsrb commented May 12, 2013

what is the maintenance strategy here? working with a CMS do users edit the JS file ( would be horrible), why not have multiple selects ( hide the non-used ) and modify the name attribute for the active one. If you worry about rendering to many DOM-elements you can have the additional selects in a <script type="stefanbc/select"> tag and use innerHTML to get the content and render it out

@jcsrb
Copy link

jcsrb commented May 12, 2013

or use an <datalist> element, and take the options tags from there, might be more semantically

@jcsrb
Copy link

jcsrb commented May 13, 2013

why not using a self executing function and passing jQuery in, no need to worry about noConflict

(function($) {
  //all your jquery code
})(jQuery

@stefanbc
Copy link
Author

I used this with a Wordpress theme and this was a quick fix that I needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment