Alex
Alex

Reputation: 189

How do I get text value from a dropdown unordered list using jQuery?

This is the unordered list:

<ul id="all-categories" class="categories-list nav nav-tabs text-center">
 <li class="category" >
     <a class="dropdown-toggle" data-toggle="dropdown" href="#">Liquor</a>
         <ul id="liquor-category" class="dropdown-menu">
            <li><a href="#">Bourbon</a></li>
            <li><a href="#">Gin</a></li>
            <li><a href="#">Rum</a></li>
            <li><a href="#">Tequila</a></li> 
            <li><a href="#">Vodka</a></li> 
            <li><a href="#">Whiskey</a></li>  
          </ul>


  </li>
   ...
</ul

And this is the code I'm using to get the text and use it as a label elsewhere on the page:

var liquor_selected  = document.querySelector('#liquor-category');
      var selected = liquor_selected.addEventListener('click',function(e){
          document.getElementById("category-name-box").innerHTML = "Liquor Sub-Category Here";
      });

It prints the generic text, but I'd like it to print the sub-category. A little help please.

Upvotes: 0

Views: 1786

Answers (2)

TomFuertes
TomFuertes

Reputation: 7270

The click handler is bound to the parent so you have to find the e.target clicked:

var liquor_selected = document.querySelector('#liquor-category');
var selected = liquor_selected.addEventListener('click', function (e) {
  document.getElementById("category-name-box").innerHTML = e.target.innerText;
});

In jQuery you can do the same:

$('#liquor-category').on('click', function (e) {
  $('#category-name-box').text($(e.target).text());
});

or you can bind to the a selector more easily in jQuery

$('#liquor-category a').on('click', function (e) {
  $('#category-name-box').text($(this).text());
});

Upvotes: 3

Trim Kadriu
Trim Kadriu

Reputation: 451

I'm assuming that you want to achieve the following (in jQuery)

Example in JsFiddle: https://jsfiddle.net/282u8avw/

HTML:

          <ul id="liquor-category" class="dropdown-menu">
            <li><a href="#">Bourbon</a></li>
            <li><a href="#">Gin</a></li>
            <li><a href="#">Rum</a></li>
            <li><a href="#">Tequila</a></li> 
            <li><a href="#">Vodka</a></li> 
            <li><a href="#">Whiskey</a></li>  
          </ul>
          <div id="category-name-box">

          </div>

Javascript/jQuery:

  $(document).ready(function() {
    $('#liquor-category a').click(function() {
      $('#category-name-box').text($(this).text());
    });
  })

Upvotes: 0

Related Questions