下拉菜单不显示所选选项

时间:2018-12-06 06:51:10

标签: javascript jquery

这是我编写的代码。

$(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正在显示选定的选项。它工作正常,但是在DropDown2中,只要我选择除第一个选项之外的任何选项,DropDown2很快就会回到第一个选项。它不显示选定的选项。

如果您需要查看我的完整代码,如下所示。

<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部分。

{% 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视图

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 %}

2 个答案:

答案 0 :(得分:1)

您必须按类而不是id来获取元素。

Getting by class

示例:$(".myClass")


Docs for getting by ID

  

以id选择器作为参数调用jQuery()(或$())将返回一个jQuery对象,其中包含 零或一个DOM元素 的集合。

示例:$("#myId")


基于对问题和答案的讨论:

编辑

// 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
        }
    });
});   

答案 1 :(得分:0)

在ajax内尝试成功:

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);
}

希望这对您有帮助