'Dropdown not showing the selected option

This is what i have coded.

$(document).on("change", "#keyDropDown, #valueOfKey", function() {
    //var chosenKey = $(this).children("option:selected").val();
    var chosenKey = $("#keyDropDown").val();
    var chosenValue = $("#valueOfKey").val();
    var data = { key: chosenKey, value: chosenValue };

    $.ajax({
        url: "value_choices",
        type: "GET",
        data: data,
        dataType: "json"
    });
});

DropDown1 is showing the selected option.It is working fine but in DropDown2 as soon as i select any option other than the first option, DropDown2 quickly gets back to first option.It is not showing the selected option.

Incase you need to see my entire code it is shown below.

<script type="text/javascript">    
$(document).on("change", "#keyDropDown, #valueOfKey", function() {
    //var chosenKey = $(this).children("option:selected").val();
    var chosenKey = $("#keyDropDown").val();
    var chosenValue = $("#valueOfKey").val();
    var data = { key: chosenKey, value: chosenValue };

    $.ajax({
        url: "value_choices",
        type: "GET",
        data: data,
        dataType: "json",
        success: function(response) {
        if (response.data) {
            var valueDropDown = $("#valueOfKey");
            valueDropDown.empty();
            for (var item of response.data) {
            valueDropDown.append(
                "<option value=" + item + ">" + item + "</option>"
            );
            }
        }
        },
        error: function(jqXHR, exception) {
        var msg = "";
        if (jqXHR.status === 0) {
            msg = "Not connect.\n Verify Network.";
        } else if (jqXHR.status == 404) {
            msg = "Requested page not found. [404]";
        } else if (jqXHR.status == 500) {
            msg = "Internal Server Error [500].";
        } else if (exception === "parsererror") {
            msg = "Requested JSON parse failed.";
        } else if (exception === "timeout") {
            msg = "Time out error.";
        } else if (exception === "abort") {
            msg = "Ajax request aborted.";
        } else {
            msg = "Uncaught Error.\n" + jqXHR.responseText;
        }
        $("#post").html(msg);
        }
    });
});   
</script>

HTML part of my code.

{% extends "base.html" %}
{% block content %}
{% if user.Journey_Shaping or user.is_superuser %}
{% load static %}
<div id="content">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form >
<div>
<input type="text" name="testPersonaName">
<br><br><br>
<select id="keyDropDown">
    <option value="name">Name</option>
    <option value="ip">ip</option>
    <option value="country">Country</option>
    <option value="city">City</option>
    <option value="region">Region</option>
    <option value="device">Device</option>
    <option value="visits">Visits</option>
    <option value="page">Pages Visited</option>
    <option value="user_id">User Id</option>
    <option value="browser">Browser</option>

 </select>
 <select id="valueOfKey" name="myvalue"></select>
 <input type="submit" name="Save">
 </div>
 </form>
 <script type="text/javascript">
  // This is the script that i have given above in my question details.  
</script>
</div>
</div> 

Django view

class ValueChoicesView(View):
def get(self, request, *args, **kwargs):
    key = request.GET.get('key')
    if key is None:
        return HttpResponse(json.dumps({
            "error": "Field 'key' is required."
        }), content_type='application/json')
    # another validation would be if the key belongs in `ModelA`

    if key == 'page':
        data = []
        key_qs = Page.objects.all().values(key)


        for item in key_qs:
            if item[key] not in data:
                data.append(item[key])

        return HttpResponse(json.dumps({"data": data}), content_type="application/json")

    else:

        data = []
        key_qs = VisitorInfo.objects.all().values(key)

        for item in key_qs:
            if item[key] not in data:
                data.append(item[key])

        return HttpResponse(json.dumps({"data": data}), content_type="application/json")
    {% endif %}
    {% endblock %}


Solution 1:[1]

You must get your elements by class, not by id.

Getting by class

Example: $(".myClass")


Docs for getting by ID

Calling jQuery() (or $()) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.

Example: $("#myId")


Based on discussion on question and this answer:

Edit

// Set "on" listener for "change" event on single element, identified by id: keyDropDown
$(document).on("change", "#keyDropDown", function() {

    $.ajax({
        url: "value_choices",
        type: "GET",
        data: {key: $(this).val()}, // $(this) is the first dropdown element, we need it's value
        dataType: "json",
        success: function(response) {
            if (response.data) {
                var secondDropdown = $("#valueOfKey"); // select 2nd dropdown
                secondDropdown.empty();                // empty dropdown

                for (var item of response.data) {      // loop response & create options
                    secondDropdown.append(
                        "<option value=" + item + ">" + item + "</option>"
                    );
                }
            }
        },
        error: function(jqXHR, exception) {
            // error handling
        }
    });
});   

Solution 2:[2]

Try This inside your ajax Success :

if(response.data) {
   var valueDropDown = $('#valueOfKey');
   valueDropDown.html();

   var dropDown = '<option value="">Select Dropdown</option>';
   $.each(response.data, function(item) {
      dropDown += '<option>' + item + '</option>';
   }

   valueDropDown.html(dropDown);
}

Hope this will help you

Solution 3:[3]

It's working for me

$(".class_name").val(value).change();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 MD. Jubair Mizan
Solution 3 Siddhartha Mukherjee