Vivek Kumar
Vivek Kumar

Reputation: 174

Unable to correctly identify selection in the dropdown button menu

Using twitter-bootstrap, I am planning to select one of the cities and change some content on the page due to the selection, but when I run the code I get all the cities and not the one I selected. How do I correctly identify the correct city. (Bonus) how do I ensure that the selection is highlighted now and has the glyphicon glyphicon-map-marker

 <ul class="nav nav-pills">
    <li class="dropdown menu-btn">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown">
        <span class="glyphicon glyphicon-map-marker"></span> San Francisco<b class="caret"></b></a>
      <ul id="fooHub" class="dropdown-menu">
            <li> <a href="#">San Jose</a> </li>
            <li> <a href="#">Silicon Valley</a> </li>
            <li> <a href="#">New York City</a> </li>
            <li> <a href="#">Paris</a> </li>
            <li> <a href="#">Silicon Valley</a> </li>
            <li> <a href="#">Tokyo</a> </li>
      </ul>
    </li>
    </ul>

Here's the js code

 $('#startupHub ').click(function () {
  console.log( $(this).text());
      });

And here's what I get on the console.

             San Jose 
             Silicon Valley 
             New York City 
             Paris 
             Silicon Valley 
             Tokyo 

and not just "Paris the city i selected.

Upvotes: 0

Views: 65

Answers (2)

kapantzak
kapantzak

Reputation: 11750

When you select #startupHub, the function outputs the text contained in this element, in this case, all the li elements.

Instead, select the anchor elements, and output each text:

$('ul.dropdown-menu > li > a').click(function() {
  //alert($(this).text());
  var that = $(this);
  $('.dropdown-menu li a').removeAttr('style');
  that.css({'background-color':'yellow'});
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav nav-pills">
    <li class="dropdown menu-btn">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown">
        <span class="glyphicon glyphicon-map-marker"></span> San Francisco<b class="caret"></b></a>
      <ul id="fooHub" class="dropdown-menu">
            <li> <a href="#">San Jose</a> </li>
            <li> <a href="#">Silicon Valley</a> </li>
            <li> <a href="#">New York City</a> </li>
            <li> <a href="#">Paris</a> </li>
            <li> <a href="#">Silicon Valley</a> </li>
            <li> <a href="#">Tokyo</a> </li>
      </ul>
    </li>
    </ul>

Upvotes: 1

Dev
Dev

Reputation: 6776

Check this demo

http://jsfiddle.net/4Lp16q5e/1/

$('#startupHub li').on('click', function(){
    console.log($(this).text());
});

Upvotes: 1

Related Questions