I have a dropdown list containing checkeboxes :
The problem is because you cannot wrap a form input in an <a>
element. The a
will intercept the click event.
To fix this you can instead wrap the inputs in a label
. You can also massively simplify your code by using the value
of the checkbox to hold the column name, and also toggle()
with the checked
state of the checkbox. You can then also hook to the change
event on the checkboxes directly as the <a>
will not be interfering with the click event. Try this:
$('#columnsListDropDown :checkbox').on('change', function() {
$("#myTable").find("[data-column='" + this.value + "']").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="dropdown-menu columnsFilterDropDownMenu" id="columnsListDropDown">
<li>
<label class="small" data-value="Type">
<input type="checkbox" checked="" value="Type">
Type
</label>
</li>
<li>
<label class="small" data-value="Release">
<input type="checkbox" checked="" value="Release">
Release
</label>
</li>
</ul>
<table id="myTable">
<tr>
<td data-column="Type">Type</td>
<td data-column="Release">Release</td>
</tr>
</table>
Use event.stopPropagation() and event.preventDefault to disable events
$('#columnsListDropDown a').on('click', function( event ) {
var input = $(this).find("input");
var columnName = $.trim($(this).text());
if (event.target.localName === "input") {
// Case where user has clicked on the input
if ($(input).is(':checked')) {
$("#myTable").find("[data-column='"+columnName+"']").show()
} else {
$("#myTable").find("[data-column='"+columnName+"']").hide()
}
} else {
event.preventDefault();
event.stopPropagation();
// Case where the user has clicked on the label, or in li element
if ($(input).is(':checked')) {
$("#myTable").find("[data-column='"+columnName+"']").hide()
$(input).prop('checked', false);
} else {
$("#myTable").find("[data-column='"+columnName+"']").show()
$(input).prop('checked', true);
}
}
return false;
});
`