0

I'm using a piece of Js code to show the selected item of a Bootstrap drop down. I have several drop downs on my ASP.NET page. When I use this code and select an item of the first (or any) dropdown, all the other drop downs change their value as well. I'm a newbie to Javascript and Bootstrap and have searched for an issue like this, but have not found any results...

JS Code (found here):

$(function(){
   $(".dropdown-menu li a").click(function(){
     $(".btn:first-child").text($(this).text());
     $(".btn:first-child").val($(this).text());
   });

});

I have tried a few interesting variations of the above. Including one that replaces ".btn:first-child" with the name of a div class for each individual drop down, and then listing all of them in the hopes that JS will know which dropdowns to change... that didn't work.

Markup Used (I am using several dropdowns in row/col-md-6):

    <div class="row">
        <div class="col-md-6">
            <div class="dropdown">
                <button class="btn btn-default dropdown-toggle" type="button" id="ddlForwardTo" data-toggle="dropdown">
                    Select a Forward To
                    <span class="caret"></span>
                </button>
              <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
              </ul>
            </div>
        </div>
        <div class="col-md-6">
            <div class="dropdown">
                <button class="btn btn-default dropdown-toggle" type="button" id="ddlManufacturing" data-toggle="dropdown">
                    Select a Manufacturing contact
                    <span class="caret"></span>
                </button>
              <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
              </ul>
            </div>
        </div>
    </div>

Any help appeciated.

UPDATE:


To sum up the frustration of more than 12 hours of work - be sure to clear your cache in Google Chrome if you get this type of error! Chrome caches Javascript.

Chrome -> Tools -> Clear browsing data... -> Select "Cached images and files" and clear it.

Community
  • 1
  • 1
Paul
  • 1,375
  • 2
  • 21
  • 55
  • You could try to navigate the DOM starting from `this` (the element that was clicked on). Look at the `closest` function. – Thilo Oct 03 '14 at 04:27

4 Answers4

1

Specifically you may consider something like:

$(function(){
   $(".dropdown-menu li a").click(function(){
       $(this).parents('.dropdown-menu').siblings('.btn').text($(this).text());
       $(this).parents('.dropdown-menu').siblings('.btn').val($(this).text());
   });
});

That way when an anchor is clicked inside of a list item within an element of the class dropdown-menu you travel up the DOM to find the .dropdown-menu parent of that anchor element. Then you only change the text and value of that specific parent. The code that you posted selected all of the dropdown menus as @jjk_charles pointed out.

JSFiddle

Joel Lubrano
  • 606
  • 3
  • 9
  • I don't know how, but this doesn't work in my environment. I see it works in the link, which is baffling me. I wonder if something is fighting with this piece of JS and not making it work correctly... – Paul Oct 03 '14 at 04:52
1

I have just had a similar problem. Things to consider are the 'id' for the button tags, and the aria-labelled by. But what solved the problem was wrapping the buttons in a "btn-group" div.

(Bootstrap 4)

<div class="btn-group"> <!-- Here -->
   <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false" id="editDetailsLink">Edit Details</button>
   <div class="dropdown-menu" x-placement="bottom-start" style="position: absolute; will-change: top, left; top: 38px; left: 0px;" aria-labelledby="editDetailsLink">
      <a class="dropdown-item" href="#">Retailer</a>
      <a class="dropdown-item" href="#">Websites</a>
   </div>
</div>
<div class="btn-group"> <!-- Here -->
   <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false" id="viewChildrenLink">Children</button>
   <div class="dropdown-menu" x-placement="bottom-start" style="position: absolute; will-change: top, left; top: 38px; left: 0px;" aria-labelledby="viewChildrenLink">
      <a class="dropdown-item" href="#">Retailers</a>
      <a class="dropdown-item" href="#">Ratings</a>
   </div>
</div>
alj
  • 2,839
  • 5
  • 27
  • 37
0

Using the selector $(".btn:first-child"), you are effectively choosing all the first child inside all elements with class btn. Instead what you want to do is, you need to write a selector in such a way that it will choose only the that is directly linked to the dropdown being selected.

You can do something similar like the below, to achieve the same:

$(this).parent().parent().parent().find(".caret").text("new text");

Of course, the above might not be an optimal thing to use directly in your code, modify the selector accordingly to suit your actual html code structure.

jjk_charles
  • 1,250
  • 11
  • 23
0

$(function(){
   $(".dropdown-menu li a").click(function(){
     $(this).parents('.dropdown').children('.btn').text($(this).text());
     $(this).parents('.dropdown').children('.btn').val($(this).text());
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">
        <div class="col-md-6">
            <div class="dropdown">
                <button class="btn btn-default dropdown-toggle" type="button" id="ddlForwardTo" data-toggle="dropdown">
                    Select a Forward To
                    <span class="caret"></span>
                </button>
              <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
              </ul>
            </div>
        </div>
        <div class="col-md-6">
            <div class="dropdown">
                <button class="btn btn-default dropdown-toggle" type="button" id="ddlManufacturing" data-toggle="dropdown">
                    Select a Manufacturing contact
                    <span class="caret"></span>
                </button>
              <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
              </ul>
            </div>
        </div>
    </div>

in you click event:

$(this).parents(".dropdown").children(".btn").text($(this).text());

possible to.replace children to find

aleha_84
  • 8,309
  • 2
  • 38
  • 46
  • I added the reference to bootstrap.min.css (I had the others). After that point, the only error in the console is one on startup, saying something in that CSS file is wrong. When I actually change the dropdown selected item, no errors in the Chrom dev tools console. It's so weird, since we have the EXACT same code... yet it works for you. – Paul Oct 03 '14 at 08:27
  • By the way, the error in the console was "unexpected token: {". Running bootstrap.min.css through the CSS validator, there are dozens of errors. I doubt that token error relates to my problem. – Paul Oct 03 '14 at 08:29
  • @Paul there is a minor chance that code posted via cdn has errors. Check your html head section, if click event won't fire and there is no errors in console it means that you place your js code in wrong place. Place some breakpoints check how it works. – aleha_84 Oct 03 '14 at 08:47
  • Well, all answers are correct. Wanna guess why? Google Chrome caches Javascript. After clearing the cache and putting in the JS in your answer (or probably any of the other ones too), the dropdowns are working properly now. GRR Chrome!!! – Paul Oct 03 '14 at 15:04
  • to avoid this in future put your code in separate file and add timestamp to it. There are alot of solutions to prevent browsers from caching js. – aleha_84 Oct 03 '14 at 18:45
  • It is in a separate file. How do I timestamp it? – Paul Oct 03 '14 at 18:53
  • @Paul read [this](http://stackoverflow.com/questions/4206224/better-way-to-prevent-browser-caching-of-javascript-files). As mentioned there, you can add timestamp to force downloading js each time, or set version manually to be sure that changes will be delivered. Example: ``. How Timestamp can be added look [here](http://stackoverflow.com/questions/11467873/how-to-append-timestamp-to-the-java-script-file-in-script-tag-url-to-avoid-cac). – aleha_84 Oct 03 '14 at 19:39