javascript - Add optgroup to dropdown created dynamically using REST, jQuery and Boostrap -
this first project using bootstrap , i'm pretty new jquery also, hope question not simple of you. have drop-down have created pulling data sharepoint using rest , ajax. part works great.
js:
$(document).ready(function () { var requesturi = "blah-blah/_api/web/lists/getbytitle('ad_db')/items?select=title,state"; var requestheaders = { "accept": "application/json;odata=verbose" } $.ajax({ url: requesturi, type: 'get', datatype: 'json', async: false, headers: requestheaders, success: function (data) { $.each(data.d.results, function (i, result) { var itemcasenumber = result.title; var itemstate = result.state; $('#mylist').append('<li role="presentation"><a role="menuitem" tabindex="-1" href="#">' + itemcasenumber + '</a></li>'); }); }, error: function ajaxerror(response) { alert(response.status + ' ' + response.statustext); } }); });
this html:
<ul class="dropdown-menu" role="menu" aria-labelledby="drop1" id="mylist"></ul>
as mentioned drop-down gets populated expected, issue. there way create optgroups based on values of variable "itemstate", contains states in sharepoint list? thanks!
bootstrap doesn't have optgroups
default use dropdown-headers
. can switch bootstrap-select plugin if want opt-groups.
anyway, example dropdown-headers:
var results = [{ state: 'az', title: 'case 1234'}, { state: 'ga', title: 'case 4212'}, { state: 'ia', title: 'case 23332'}, { state: 'la', title: 'case 2221' }, { state: 'ks', title: 'case 4432' }, { state: 'md', title: 'case 2882'}, { state: 'ks', title: 'case 1022' }, { state: 'ga', title: 'case 1111' }]; // sort results state field. uses comparestates function below results.sort(comparestates); var laststate = ''; $.each(results, function (i, result) { var itemcasenumber = result.title; var itemstate = result.state; // add new header each state if (itemstate != laststate) { // don't add divider line if first state in dropdown if (i>0) { $('#mylist').append('<li role="presentation" class="divider"></li>'); } laststate = itemstate; $('#mylist').append('<li role="presentation" class="dropdown-header">'+itemstate+'</li>'); } $('#mylist').append('<li role="presentation"><a role="menuitem" tabindex="-1" href="#">' + itemcasenumber + '</a></li>'); }); function comparestates(a,b) { if (a.state < b.state) return -1; if (a.state > b.state) return 1; return 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/> <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownmenu1" data-toggle="dropdown"> dropdown <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu" aria-labelledby="drop1" id="mylist"></ul> </div>
Comments
Post a Comment