How to change bootstrap dropdown titile to selection title

时间:2016-07-11 18:55:08

标签: twitter-bootstrap asp.net-mvc-5.2

I've been trying to change the title of the dropdown menu to the selected item. It works in jsfiddle, but in my project it won't. Here is my code:

<script type="text/javascript">
$(".dropdown-menu li a").click(function() {
    $('#countries').html($(this).text() + ' <span class="caret"></span>');
    $('#countries').val($(this).data('value'));
});

<div class="dropdown" style="text-align:center">
                        <button id="countries" class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" href="#" style="width:50%">
                            Country
                            <span class="caret"></span>
                        </button>
                        <ul class="dropdown-menu" style="width:50%; text-align:center">
                            <li><a href="#" data-value="Afghanistan ">  Afghanistan   </a>       </li>
                            <li><a href="#" data-value="Albania ">  Albania   </a>       </li>
                            <li><a href="#" data-value="Algeria ">  Algeria   </a>       </li>
                            <li><a href="#" data-value="American Samoa ">  American Samoa   </a>       </li>
                            <li><a href="#" data-value="Andorra ">  Andorra   </a>       </li>      
                        </ul>
                    </div>

The list contains all countries, but for this post I left a majority of them out. Any ideas why this isn't working in my project? Thanks.

1 个答案:

答案 0 :(得分:0)

What I would recommend is changing how you are targeting the button in js.

$(".dropdown-menu li a").click(function() {
   // Gets the button by it's class name
   $('.dropdown-toggle').html($(this).text() + ' <span class="caret"></span>');
   $('.dropdown-toggle').val($(this).data('value');
}

However, this may be a problem if you are planning on having more than one '.dropdown-toggle' on the page.

In that case, you should give the button an id and then target that instead.

<button id="country" class="btn btn-default dropdown-toggle dropcust" type="button" data-toggle="dropdown" href="#" style="width:50%">
   Country <span class="caret"></span>
</button>


$('#country).html($(this).text() + ' <span class="caret"></span>');
$('#country').val($(this).data('value');