Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show selected option in bootstrap dropdown list menu

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?

like image 376
onedevteam.com Avatar asked Oct 29 '15 11:10

onedevteam.com


People also ask

How do you display a selected value in a drop-down list?

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.

How do I get selected value from a Bootstrap select drop down?

You can get the selected value's text with $(this). find("option:selected"). text() .

How do I style a dropdown in Bootstrap?

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.

How do I add a button to a dropdown list?

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.


1 Answers

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

like image 112
Ganesh Kumar Avatar answered Sep 21 '22 04:09

Ganesh Kumar