Reputation: 77
JSFiddle Here
This is a list of checkboxes inside a dropdown menu. I would like to be able to click the anchor tags' text to select the corresponding checkbox. However, I currently have it set to <a href="#">
which simply closes the dropdown and goes to top of page (on my own version, not JSFiddle, because it is on an overlay).
I saw a solution that selected the checkbox but the dropdown still closed on each click, is there a simple way to fix this?
Upvotes: 3
Views: 2742
Reputation: 9804
you can achive it like this.
$('a').on("click",function(e) {
e.preventDefault();
var checkbox = $(this).children("input");
$(checkbox[0]).attr('checked', !checkbox.attr('checked'));
});
fiddle : http://jsfiddle.net/u614sy0L/5/
Upvotes: 0
Reputation: 7078
$('.dropdown-menu a').click(function(event){
event.preventDefault();
var checkBox = $(this).find(':checkbox');
checkBox.prop("checked", !checkBox.prop("checked"));
})
@import url('https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/css/bootstrap.min.css');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>
<label for="display">Display</label><br/>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="display" data-toggle="dropdown">
Select Options
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>
<a href="#">
<input type="checkbox">Item 1</a>
</li>
<li>
<a href="#">
<input type="checkbox">Item 2</a>
</li>
<li>
<a href="#">
<input type="checkbox">Item 3</a>
</li>
</ul>
</div>
Upvotes: 0
Reputation: 2516
You can use labels for this functionality. Replace your <ul>
list with this one.
<ul class="dropdown-menu">
<li>
<input type="checkbox" id="check_1"/>
<label for="check_1">Item 1</label>
</li>
<li>
<input type="checkbox" id="check_2"/>
<label for="check_2">Item 2</label>
</li>
<li>
<input type="checkbox" id="check_3"/>
<label for="check_3">Item 3</label>
</li>
</ul>
This will help you
Upvotes: 6