[英]Hide the drop down menu when clicking outside
I have a dropdown menu with checkboxes inside. 我有一个带有复选框的下拉菜单。 I want to close the dropdown when the users click outside. 当用户单击外部时,我想关闭下拉菜单。
My code is: 我的代码是:
<form>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
</select>
</div>
<div class="checkboxes" id="checkboxes">
@{
if (ViewBag.DataActiveEmployee == null || ((IEnumerable<MvcApplication1.Models.ActiveUsersList>)ViewBag.DataActiveEmployee).Count() == 0)
{
//@:<h3>No records were processed.</h3>
}
else
{
foreach (var usr in ViewBag.DataActiveEmployee)
{
<label id="userName">@usr.EmployeeName</label>
<input class="checked" type="checkbox" name="search_emp" id="search_emp" value=@usr.EmployeeName>
@:
}
}
}
</div>
</div>
JS JS
<script>
var expanded = false;
checkboxes.style.display = "none";
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
$('multiselect').click(function () {
$("#checkboxes").hide();
});
The problem is inside the second function of JavaScript because when I press outside, nothing is happening. 问题出在JavaScript的第二个函数内部,因为当我按外部时,什么也没发生。
Please help. 请帮忙。
Try using the event.target
to handle click events: 尝试使用event.target
处理点击事件:
UPDATE 更新
$(document).on('click', '.multiselect .selectBox', function(e) { e.stopImmediatePropagation(); $('#checkboxes').show(); }); $('body').on('click', function(e) { if (e.target.id != 'checkboxes' && $(e.target).closest('#checkboxes').length == 0) { $('#checkboxes').hide(); } });
#checkboxes, .multiselect { padding:15px; border:1px solid #d8d8d8; } .selectBox { display: inline; } #checkboxes { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="multiselect"> <div class="selectBox"> <select> </select> </div> <div class="checkboxes" id="checkboxes"> <label id="userName">Employee 1</label> <input class="checked" type="checkbox" name="search_emp" id="emp_1" value="val_1"> <label id="userName">Employee 1</label> <input class="checked" type="checkbox" name="search_emp" id="emp_1" value="val_1"> </div> </div>
Check if the target click on dom is the dropdown itself or not as 检查目标点击dom本身是否为下拉列表
$(document).on("click", function(event){
var $trigger = $(".checkboxes");
if($trigger !== event.target && !$trigger.has(event.target).length){
$(".checkboxes").hide();
}
});
It should work. 它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.