JQuery Select2子项未显示为已选中

时间:2014-10-22 09:53:43

标签: javascript jquery jquery-select2 angularjs-select2

我在数据中有一个带有“children”属性的select2框,它按预期呈现。但是在编辑屏幕中,当我们选择子元素时,其父元素在下拉列表中保持不变。例如,当我们在添加表单中选择“直播乐队”但编辑表单显示“娱乐”时选中。请查找我正在使用的数据格式和源代码。请帮我解决这个问题。

数据

[
    {
        "id": "12",
        "text": "Personal Chef",
        "parent": "0",
        "order": 0
    },
    {
        "id": "11",
        "text": "Entertainment",
        "parent": "0",
        "order": 1,
        "children": [
            {
                "id": "37",
                "text": "DJ’s",
                "parent": "11",
                "order": 0
            },
            {
                "id": "38",
                "text": "Live Band",
                "parent": "11",
                "order": 1
            },
            {
                "id": "36",
                "text": "Clowns - Kids parties",
                "parent": "11",
                "order": 2
            }
        ]
    },
    {
        "id": "10",
        "text": "Motorcycle Repair",
        "parent": "0",
        "order": 2
    }
]

源代码:

$(".search-result-box").select2({
    placeholder: "eg: 1967 Stingray Mechanic",
    multiple: false,
    width: 225,
    selectOnBlur: true,
    data: data
});

$(".search-result-box").select2('val', 38); // Tried select2('val', "38") also.

1 个答案:

答案 0 :(得分:2)

我刚刚在plunker中尝试了您的select2示例,并且按照您的预期进行了工作。

如果您正在寻找其他任何内容,请查看并告诉我们。另请注意您的jquery,select2版本。

<强> HTML:

<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@1.7.1" data-semver="1.7.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <link data-require="select2@*" data-semver="3.5.1" rel="stylesheet" href="//cdn.jsdelivr.net/select2/3.4.5/select2.css" />
  <script data-require="select2@*" data-semver="3.5.1" src="//cdn.jsdelivr.net/select2/3.5.1/select2.min.js"></script>

  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>

  <input type="hidden" class="search-result-box" />

</body>

</html>

JavaScript文件:

$(function() {

   $(".search-result-box").select2({
     placeholder: "eg: 1967 Stingray Mechanic",
     multiple: false,
     width: 225,
     selectOnBlur: true,
     data: data
   });

  $(".search-result-box").select2('val', 38); // Tried select2('val', "38") also.

});