Convert html select dropdown to single button Nav bar

Viewed 99

I have requirement for dynamic menu Navbar output like below with this design.

enter image description here

But now i am getting like below

enter image description here

I am getting dynamic menu data from database below is my code

  <select id="dropdownlist" class="form-control" style="color:black">
                        </select>


  $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "/CDO/Menu",
                data: "{}",
                success: function (data) {
                    var s = '<option>All History</option>';
                    for (var i = 0; i < data.length; i++) {
                        s += '<option value="' + data[i].Id + '">' + data[i].type + '</option>';
                    }
                    $("#dropdownlist").html(s);
                }
            });
1 Answers

You can create a tags for button dropdown inside for-loop and then add that generated html inside your dropdown-menu.

Demo Code :

//just for demo :)
var data = [{
  "Id": "1",
  "type": "abc"
}, {
  "Id": "2",
  "type": "abc2"
}]
$(document).ready(function() {
  var s = "";
  /* $.ajax({
     type: "GET",
     url: "/CDO/Menu",
     data: "{}",
     success: function(data) {*/
  for (var i = 0; i < data.length; i++) {
    //generate a tag here ..
    s += ' <a class="dropdown-item" href="#"> ' + data[i].Id + ' - Type : ' + data[i].type + '</a>'

  }
  $("#dropdownlist").html(s);
  /* }
  });*/


  //on click of a tag inside dropdown
  $(document).on('click', '.dropdown-menu a', function() {
    console.log($(this).text())
    $(".dropdown-toggle").text($(this).text()) //change text of button if needed
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<div class="dropdown">
  <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    All History
  </button>
  <div class="dropdown-menu" id="dropdownlist">
    <!--here options will come -->
  </div>
</div>

Related