Search code examples
javascriptjqueryjquery-select2angularjs-select2

JQuery Select2 Child item not shows as selected


I have a select2 box with "children" attribute in the data and it render as expected. But in the edit screen when we select a child element its parent element persisted in the dropdown. For example, when we select "Live Band" while in the add form but the edit form shows "Entertainment" as selected. Please find the data format and source code I am using. Please help me to resolve this issue.

Data

[
    {
        "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
    }
]

Source Code:

$(".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.

Solution

  • I just tried your select2 example in the plunker and it's working as per your expectation.

    Please have a look and let me know if you are looking for anything else. Please also mention your jquery,select2 versions as well.

    HTML:

    <!DOCTYPE html>
    <html>
    
    <head>
      <script data-require="[email protected]" 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 File:

    $(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.
    
    });