Nirav Joshi
Nirav Joshi

Reputation: 2960

bootstrap dropdown select default value not working

i m using bootstrap dropdown menu

$(".dropdown-menu li a").on('click',function(){
    var selText = $(this).text();
    $(this).parents('.dropdown').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
    $(".default_option").remove();
    $(".dropdown-menu").prepend("<li class='default_option'><a>Kies behandeling</a></li>");
});
#treatment-modal .caret {
    display: inline-block;
    width: 0;
    height: 0;
    margin-left: 2px;
    vertical-align: middle;
    border-top: 4px dashed;
    border-top: 4px solid\9;
    border-right: 4px solid transparent;
    border-left: 4px solid transparent;
}
#treatment-modal .dropdown-menu>li>a {
    display: inline-block;
    padding: 12px;
    clear: both;
    font-weight: 400;
    line-height: 1;
    color: #333;
    white-space: nowrap;
    width: 100%;
    cursor: pointer;
}
#treatment-modal .dropdown-menu li {
    margin: 0;
    padding: 0;
    line-height: 0;
}
#treatment-modal button.btn.btn-default.dropdown-toggle {
    margin: 5px 0 0;
    text-align: left;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="treatment-modal">
   <div class="dropdown">
      <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false">Kies behandeling<span class="caret"></span></button>
      <ul class="dropdown-menu treatment-select">
         <li>
            <a value="37"><span class="pull-left">hair wash and treatment (60min)</span><span class="pull-right">€30.00</span></a>
         </li>
      </ul>
   </div>
</div>

When i m trying to select option it is working properly and showing me as replacement of the text of drop-down LIKE CONVENTIONAL SELECT DROP-DOWN

But when i try to prepend some value in dropdown than i click on that prepended value at that time default selection not working.

Looking for Help.

Upvotes: 0

Views: 1930

Answers (1)

Nidhin Chandran
Nidhin Chandran

Reputation: 856

The default element is added dynamically to the menu so you need to edit the .on() function for the new element to bind properly.

$(document).on('click', ".dropdown-menu li a", function() {
    var selText = $(this).text();
    $(this).parents('.dropdown').find('.dropdown-toggle').html(selText + ' <span class="caret"></span>');
    $(".default_option").remove();
    $(".dropdown-menu").prepend("<li class='default_option'><a>Kies behandeling</a></li>");
});

check fiddle here

Upvotes: 2

Related Questions