Need help with linked selects using ajax and jquery

Need help with linked selects using ajax and jquery

I have a django 1.11 based web site, and I am trying to use jQuery to update a select box based on a selection in another select box on the same page. I am not a jQuery or javascript developer, so I am a little lost.

This is my script -
  1. var $ = django.jQuery;

    $(function() {
        var t = $("#id_documentmetadatavalue_set-0-metadata");
        t.change(function(){
            if (t.val() !== '') {
             
                alert("change");

                var selected = [];
                $("#id_documentmetadatavalue_set-0-metadata :selected").each(function(i, sel){
                  selected.push($(sel).val());
                });
             
                alert(selected);
                $.ajax({
                    url: '/ajax/metadatavalue_query/' + t.val(),
                    dataType: 'json',
                    success:function(data) {
                        data = $.parseJSON(JSON.stringify(data));
                        var options;
                        options = '<option value>---------</option>';
                        $.each(data, function(index,item) {
                            options += '<option value="' + item.id + '">' + item.value + '</option>';
                        });
                     
                        alert(options);
                       
                                           
                        $("#id_documentmetadatavalue_set-0-metadataValue").html(options);
                         
                       $("#id_documentmetadatavalue_set-0-metadataValue").val($("#id_documentmetadatavalue_set-0-metadataValue option:first").val());
                    }
                });
            }
            });
            $("#id_documentmetadatavalue_set-0-metadata").trigger('change');
        });

The django end of the ajax request works. When I load the django admin page and select the id_documentmetadatavalue_set-0-metadata, the script runs, fills the id_documentmetadatavalue_set-0-metadataValue select box with the correct values.

I have two problems -

1. When I hit save on the page, the script runs again, blanks out the id_documentmetadatavalue_set-0-metadataValue select box and I get an error (ie missing value) and can't save the page. I guess it has something to do with the trigger statement at the end of the script, but really no idea how to fix this issue.

2. I can add more id_documentmetadata_set-*-metadata and id_documentmetadatavalue_set-*-metadataValue controls to the page. They are numbered sequentially, starting at 0 (ie, the * has values 0, 1, 2, 3....). How do I modify the script to accommodate an unknown number of these controls?

Thanks!

Mark