Skip to content

Instantly share code, notes, and snippets.

@ranelpadon
Created August 27, 2017 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranelpadon/c49fab04eb845f0743d0abbcd181dfc5 to your computer and use it in GitHub Desktop.
Save ranelpadon/c49fab04eb845f0743d0abbcd181dfc5 to your computer and use it in GitHub Desktop.
Update the select list field B based on the currently selected option in select list field A. For example, when you select a particular Music Genre only the related Artist should show. Other common use cases/relationships are Company/Contact Info, Country/City, or Brand/Products.
(function($) {
$(function() {
// Artist's select option values will depend on
// the Genre's selected option.
var $genreSelectWidget = $('#id_genre');
var $artistSelectWidget = $('#id_artist');
var artistSelectWidgetInitial = $artistSelectWidget.val()
// Adjust Artists based on the selected Genre.
function adjustArtistOptions(preSelectedOption) {
var selectedGenre = $genreSelectWidget.find(':selected').text();
$.getJSON('/list_artists/?genre=' + selectedGenre, function(data) {
var $artistNonEmptyOptions = $artistSelectWidget.find('option:not(:first)');
$artistNonEmptyOptions.remove();
// Rebuild the options.
var artistOptions = []
$.each(data, function(dataIndex, artist) {
var artistOption = $('<option>', {
value: artist.id,
text : artist.name
});
artistOptions.push(artistOption);
});
$artistSelectWidget.append(artistOptions);
// Auto-select the option that is previously saved in db,
// or the one set as initial value.
if (preSelectedOption) {
$artistSelectWidget.val(preSelectedOption);
}
// Optional behavior.
// Auto-select the first non-empty option for better UX.
else {
$artistSelectWidget.find('option:nth-child(2)').prop('selected', true);
}
});
}
// On page load, use the preselected value if there's any.
adjustArtistOptions(artistSelectWidgetInitial);
// As the user starts interacting with the Genre select list field,
// refresh the Artist select list field options accordingly.
$genreSelectWidget.change(function() {
adjustArtistOptions();
});
});
})(django.jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment