I have dropdown list in my bootstrap menu.
<li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#">Chose option<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Option 1</a></li> <li><a href="#">Option 2</a></li> <li><a href="#">Option 3</a></li> <li><a href="#">Option 4</a></li> </ul> </li>
I'm trying to get selected option in dropdown as title of dropdown instead of "chose option", as it is now. I have tried several solutions found on this and some other sites, but can't make any of them to work.
Can someone help with this?
Method 1: Using the value property: The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.
You can get the selected value's text with $(this). find("option:selected"). text() .
To open the dropdown menu, use a button or a link with a class of .dropdown-toggle and the data-toggle="dropdown" attribute. The .caret class creates a caret arrow icon (), which indicates that the button is a dropdown. Add the .dropdown-menu class to a <ul> element to actually build the dropdown menu.
Example Explained Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element. Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it. Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.
This should work for you:
<div class="dropdown"> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#"> <span id="selected">Chose option</span><span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Option 1</a></li> <li><a href="#">Option 2</a></li> <li><a href="#">Option 3</a></li> <li><a href="#">Option 4</a></li> </ul> </div>
And the script:
$('.dropdown-menu a').click(function(){ $('#selected').text($(this).text()); });
You need to wrap the text 'Choose option' inside <span>
to modify its value on selection.
Here is the working code: http://liveweave.com/U4BpiH
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With