LearningJS888 LearningJS888 - 1 month ago 7
jQuery Question

Pop selection off dropdown menu

I have a question about popping selection from dropdown off the menu. I have a dropdown that gets dynamically populated with people's names, and I'd like the name selected to pop off the drop down menu and appear in a div next to it. The dropdown menu:

<div class="col-md-4">
<div class="dropdown">
<button style="width: 100%;" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select Group Members
<span class="caret"></span></button>
<ul class="dropdown-menu scrollable-menu" role="menu">
{{#each users}}
<li data-uid={{this.u_id}}>{{this.full_name}}</li>
{{/each}}
</ul>
</div>
</div>


And the div I'd like the information (name) to appear:

<div class="col-lg-4">
<h2 class="text-center" style="margin-top: 0;">Selected Group Members</h2>
<ul class="list-unstyled">
<li data-uid={{this.u_id}} class="text-center">{{this.full_name}}</li>
</ul>
</div>


I'm imagining this can be done with some jQuery, which I'm unfortunately not too great at, so I'm not quite sure how to do this. Any help is appreciated!

Answer

This should does the work. Please check.

// selected element
var selections = [];
// container that holds selections 
var listContainer = $('.container .list-unstyled');

// sorting array of objects by provided field
var sortBy = function (arr, field) {
    return arr.sort(function (a, b) {
       if (a[field].toLowerCase() < b[field].toLowerCase()) return -1;
       if (a[field].toLowerCase() > b[field].toLowerCase()) return 1;
       return 0;
    });
};

// redraw list on container
var reorder = function(){
   listContainer.html('');
   for(var i = 0; i < selections.length; i++){
      listContainer.append('<li data-uid=' + selections.id + '>' + selections.value + '</li>');
   }
}

// list items click handler
$('ul.list-unstyled li').click(function(){
   selections.push({
      id: $(this).attr('data-uid'),
      value: $(this).text()
   });

  selections = sortBy(selections, 'name');
});