SACHIN RINDER SACHIN RINDER - 5 months ago 10
jQuery Question

How to write jquery for different dropdowns

I am trying to make 2 different drop downs in a page. I've wrote this bootstrap code -

<div class="box">
<div class="box-header black">
<div class="col-md-1"></div>
<div class="col-md-3">
Set Point Management:
</div>
<div class="col-md-1">
<div class="btn-group">
<a class="btn dropdown-toggle info" data-toggle="dropdown" href="#">
Optimized <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="#">Manual</a></li>
<li><a href="#">Scheduled</a></li>
<li><a href="#">Optimized</a></li>
</ul>
</div>
</div>
<div class="clearfix"></div>
</div>

<div class="box-body">
<div class="col-md-1"></div>
<div class="col-sm-3 col-md-3">
<div class="btn-group">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Select Operator <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="#">=</a></li>
<li><a href="#">></a></li>
<li><a href="#"><</a></li>
</ul>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>


and I'm using this jquery to change the name of dropdown with the selected component-

<script type="text/javascript">
$(".dropdown-menu li a").click(function () {
$(".btn:first-child").html($(this).text() + ' <span class="caret"></span>');
});
</script>


It was working fine with one dropdown. But with 2 dropdowns, when I select any item in one dropdown, name tag changes in both dropdowns.

I tried to differentiate them by giving id, but didn't work.
So how should I write jquery for it ?

(step wise answer would be helpful)

Answer

The {selector}:first-child pseudo class points to the first child of the given selector within a parent element. Since your line $(".btn:first-child") don't specify a parent, both .btn-elements on your page are selected. If you change that line to the following it should work:

$(".btn:first-child", $(this).closest("div.btn-group")).html(...)

The second parameter gives the element in which to search for the selector, which in this case becomes the closest div to the a-element with the btn-group class.