Twitter Bootstrap: How do I get the selected value of dropdown?

I need to get the value a user selects from a twitter bootstrap dropdown. Once the user selects a value I want the dropdown to display that value. So, the user selects 'pending' then I want to change the selected dropdown value from that and, when the user completes the form, I want to retrieve the selected value. Would someone be able to point me in the right direction?

<div class="btn-group">
  <i class="dropdown-arrow dropdown-arrow-inverse"></i>
  <button class="btn btn-primary">status</button>
  <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu dropdown-inverse">
    <li><a href="#fakelink">pending</a></li>
    <li><a href="#fakelink">active</a></li>
    <li><a href="#fakelink">discontinued</a></li>
  </ul>
</div>

Upvotes: 14

Views: 42703

Answers (4)

Rohit Suthar
Rohit Suthar

Reputation: 3628

Try like this -

$(document.body).on('click', '.dropdown-menu li a', function (e) {
    alert($(this).text());
});

Demo - Fiddle

Upvotes: 0

BandfuzzAlex
BandfuzzAlex

Reputation: 171

I had the same issue. The solution is pretty easy and I think the answers above may be overcomplicating a bit.

Just use $(this).text()

Assign a class name to the "" bit then..

$(".yourUlClassName li a").click( function() {
    var yourText = $(this).text();
});

Upvotes: 14

Mohsen Rasouli
Mohsen Rasouli

Reputation: 352

you can try this:

u can use class or id for selector to select easier the element. for use the value also u can use the value in u javascript with jQuery.

    $().ready(function(){
        $('a').click(function(){
            var value = $(this).text();
            alert(value);
        });
    });

Demo: http://jsfiddle.net/mr_mohsen_rasouli/A8m39/

Upvotes: 2

PSL
PSL

Reputation: 123739

Bootstrap provides you with minimum required functionality for your implementation, they aren't dropdowns instead they are mere ul, li's with css applied on it and some events registered in the bootstrap plugin for toggling the button to display them as dropdown. This one you need to do on your own.

Set up some identifier to the status button say a className btnStatus and bind a click event to the dropdown links. and do something like this?

$('.dropdown-inverse li > a').click(function(e){
    $('.btnStatus').text(this.innerHTML);
});

Demo

Upvotes: 19

Related Questions