Reputation: 451
I want to add a drop down to select cities but don't know how to select a default value before selection. I am using Bootstrap 3.
Here is the HTML Markup:
<div class="btn-group">
<a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">
Select City <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="col-md-12 col-sm-12 col-xs-12 no-gutter">
<h5><img src="images/pk-flag.png" /> PAKISTAN</h5>
</div><!-- col-md-12 -->
<div class="col-md-12 col-sm-12 col-xs-12 no-gutter">
<div class="col-md-6 col-sm-6 col-xs-6">
<li><a href="#">Lahore</a></li>
</div><!-- col-md-6 -->
<div class="col-md-6 col-sm-6 col-xs-6">
<li><a href="#">Islamabad</a></li>
</div><!-- col-md-6 -->
</div><!-- col-md-12 -->
<div class="col-md-12 col-sm-12 col-xs-12 no-gutter">
<div class="col-md-6 col-sm-6 col-xs-6">
<li><a href="#">Karachi</a></li>
</div><!-- col-md-6 -->
<div class="col-md-6 col-sm-6 col-xs-6">
<li><a href="#">Faisalabad</a></li>
</div><!-- col-md-6 -->
</div><!-- col-md-12 -->
<div class="col-md-12 col-sm-12 col-xs-12 no-gutter">
<div class="col-md-6 col-sm-6 col-xs-6">
<li><a href="#">Multan</a></li>
</div><!-- col-md-6 -->
<div class="col-md-6 col-sm-6 col-xs-6">
<li><a href="#">KPK</a></li>
</div><!-- col-md-6 -->
</div><!-- col-md-12 -->
</div><!-- col-md-12 -->
</ul>
</div><!-- btn-group -->
Here is the JS code:
/* City Selection DropDown */
$(".dropdown-menu li a").click(function()
{
var selText = $(this).text();
$(this).parents('.btn-group')
.find('.dropdown-toggle')
.html(selText+' <span class="caret"></span>');
});
Here is the JsFiddle.
Upvotes: 0
Views: 9529
Reputation: 1232
You have to add following code after your js code
$(".dropdown-menu li a")[2].click();
For example:
/* City Selection DropDown */
$(document).ready(function(){
$(".dropdown-menu li a").click(function(){
var selText = $(this).text();
$(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
});
$(".dropdown-menu li a")[2].click();
});
You can put any array value instead of 2.
Upvotes: 5