Change form field options dynamically (and restore previously selected options) using jQuery
- by Martin
I'm fairly new to both jQuery and JavaScript so can anyone please point out what I'm missing here?
I have a form with multiple pairs of select fields, where the content of the second field relies on the selection of the first one.
Once a value is chosen from the first one then a piece of jQuery code empties the corresponding second select options, gets new values as JSON and inserts them as new select values. All of this works with the code I've written.
However if a user has chosen a second value, I'd like to restore it if possible (meaning if the new values also include the one previously selected).
I tried to do this by first saving the second value and then trying to set it once the new options have been inserted. This did not work. However when trying to debug I inserted an alert() just before restoring the second value and with that in there it does work...
Am I missing something very basic here? Any help would be appreciated.
HTML:
<select name="party-0-first" id="id_party-0-first">
<option value="" selected="selected">---------</option>
<option value="1">first_value1</option>
<option value="2">first_value2</option>
<option value="3">first_value3</option>
<option value="4">first_value4</option>
</select>
<select name="party-0-second" id="id_party-0-second">
<option value="" selected="selected">---------</option>
<option value="1">second_value1</option>
<option value="2">second_value2</option>
<option value="3">second_value3</option>
<option value="4">second_value4</option>
</select>
<select name="party-1-first" id="id_party-1-first">
...
JavaScript:
$.fn.setSecond = function() {
var divName = $(this).attr("name");
divName = divName.replace('-first', '');
divName = divName.replace('party-', '');
// Save the currently selected value of the "second" select box
// This seems to work properly
setValue = $('#id_party-' + divName + '-second').val();
// Get the new values
$.getJSON("/json_opsys/", { client: $(this).val() },
function(data){
$('#id_party-' + divName + '-second').empty();
$('#id_party-' + divName + '-second').append('<option value="" selected="selected">---------</option>');
$.each(data, function(i, item){
$('#id_party-' + divName + '-second').append('<option value="' + item.pk + '">' + item.fields.name + '</option>');
});
});
// Here I try to restore the selected value
// This does not work normally, however if I place a javascript alert() before
// this for some reason it does work
$('#id_party-' + divName + '-second').val(setValue);
$(document).ready(function(){
$('[id*=first]').change(function() {
$(this).setSecond();
});
});