Apsed1976 Apsed1976 - 2 months ago 6
Javascript Question

How to set both display and data values for Bootstrap Dropdown?

I have a typical Bootstrap Dropdown like this:

<div class="btn-group">
<button type="button" class="btn btn-lg btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Default option<span class="caret"></span></button>
<ul id="mySelect" class="dropdown-menu">
<li data-value="10" role="presentation"><a href="#">Option 1</a></li>
<li data-value="20" role="presentation"><a href="#">Option 2</a></li>
</ul>
</div>


My attempt on setting display and data values is following:

var mySelect= $('#mySelect');
mySelect.on('click', 'li', function () {
updateManufacturerIdSelect($(this).data('value'));
});

$(".dropdown-menu li a").click(function () {
var selText = $(this).text();
$(this).parents('.btn-group').find('.dropdown-toggle').html(selText + ' <span class="caret"></span>');
});


Although display value changes, I can't change
data-value
as the
on('click', 'li')
event doesn't fire. Preferably I'd like to do both on the same type of event. But due to lack of experience I can't think of a better implementation.

Answer

This line:

$(this).parents('.btn-group').find('.dropdown-toggle')

must be changed with:

$(this).closest('.btn-group').find('.btn')

And you can use this event for both:

$(".dropdown-menu li a").click(function () {

The snippet:

function updateManufacturerIdSelect(val) {
  console.log('updateManufacturerIdSelect: ' + val);
}

$(".dropdown-menu li a").click(function () {
  var selText = $(this).text();
  $(this).closest('.btn-group').find('.btn').html(selText + ' <span class="caret"></span>');
  updateManufacturerIdSelect($(this).closest('li').data('value'));
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>




<div class="btn-group">
    <button type="button" class="btn btn-lg btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Default option<span class="caret"></span></button>
    <ul id="mySelect" class="dropdown-menu">
        <li data-value="10" role="presentation"><a href="#">Option 1</a></li>
        <li data-value="20" role="presentation"><a href="#">Option 2</a></li>
    </ul>
</div>

Comments