Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected text from bootstrap dropdown

I have a bootstrap dropdown, and I want to keep the text of what is selected. I have tried most of the ways tried here, Get Value From html drop down menu in jquery , but there was never really an answer given, so I am still stuck.

<div id="tableDiv" class="dropdown">
    <button id="tableButton" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
        Table
        <span class="caret"></span>
    </button>
    <ul id="tableMenu" class="dropdown-menu">
        <li><a href="#">Att1</a></li>
        <li><a href="#">Att2</a></li>
        <li><a href="#">Att3</a></li>
    </ul>
</div>

I have a js function that looks as follows

$("#tableMenu").click(function(){
  var selText = $("#tableMenu").text();
  document.getElementById("tableButton").innerHTML=selText;
});

but as explained in the above link, $("#tableMenu").text(); returns everything in the dropdown as a string, not just the one wanted. How do I get the text just from the one selected.

like image 914
Joe Johnson Avatar asked Mar 09 '16 07:03

Joe Johnson


2 Answers

You need to attach the click() handler to the a element within the ul that gets toggled. You can then retrieve the text() of that element and set it to the related button. Try this:

$("#tableMenu a").on('click', function(e) {
  e.preventDefault(); // cancel the link behaviour
  var selText = $(this).text();
  $("#tableButton").text(selText);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tableDiv" class="dropdown">
  <button id="tableButton" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
        Table
        <span class="caret"></span>
    </button>
  <ul id="tableMenu" class="dropdown-menu">
    <li><a href="#">Att1</a></li>
    <li><a href="#">Att2</a></li>
    <li><a href="#">Att3</a></li>
  </ul>
</div>
like image 151
Rory McCrossan Avatar answered Sep 21 '22 02:09

Rory McCrossan


Have you tried using an actual HTML drop down box and not an unordered list?

  <select name="tableMenu" id="tableMenu" class="dropdown-menu">
    <option value="Att1">Att1</option>
    <option value="Att2">Att2</option>
    <option value="Att3">Att3</option>
  </select>

You should then be able to use:

var selText= document.getElementById("tableMenu").value;
like image 26
Steve Avatar answered Sep 22 '22 02:09

Steve