I'm trying to create an accordion menu using jQuery UI Autocomplete with the JSON result. The JSON object items
contains data with label
, name
, and value
properties. I want to group similar name
values together and use one of them as the title for the accordion section.
Here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CatComplete</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4" id="all-list">
<label for="search">Search:</label>
<input id="search" class="form-control" />
<div class="list-group panel" id="accordion"></div>
</div>
</div>
</div>
</body>
</html>
And this is my JavaScript code:
var items = [
{label: "TY2021H", name: "10-Yr T-Notes", value: "TY2021H"},
{label: "TY2020Z-TY2021H", name: "10-Yr T-Notes Spread", value: "TY2020Z-TY2021H"},
{label: "TY2021H-TY2021M", name: "10-Yr T-Notes Spread", value: "TY2021H-TY2021M"},
{label: "TY2020Z-2*TY2021H+TY2021M", name: "10-Yr T-Notes Butterfly", value: "TY2020Z-2*TY2021H+TY2021M"}
];
var myUL = $("#accordion");
myUL.empty();
var currentName = "";
for (var i = 0; i <= items.length - 1; i++) {
var label = items[i].label;
if (items[i].name != currentName) {
currentName = items[i].name;
list +=
'<a href="#demo' +
i +
'" class="list-group-item list-group-item-info" data-toggle="collapse" data-parent="#accordion">' +
currentName +
' <span id="opnClsSign" class="glyphicon glyphicon-menu-down"></span></a>';
list += '<div class="collapse in" id="demo' + i + '">';
}
list += '<a href="#" class="list-group-item">' + label + "</a>";
}
list += "</div>";
myUL.append(list);
The current implementation creates an accordion with the items from the JSON object. However, the accordion titles should be based on the unique name
values, and each section should contain items with the same name
. Currently, it doesn't group the items correctly.
How can I modify the JavaScript code to achieve this behavior and create an accordion menu with the appropriate titles for each group? Any insights or suggestions would be greatly appreciated. Thank you!
I was able to resolve the issue myself, and I've included the final source code here:
Feel free to check it out! If you have any questions or need further assistance, don't hesitate to ask. Happy coding!