Checkbox Stays Checked When Clicking On It In A Dropdown
I have a dropdown list containing checkeboxes :
Solution 1:
The problem is because you cannot wrap a form input in an
<a>
element. Thea
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 thevalue
of the checkbox to hold the column name, and alsotoggle()
with thechecked
state of the checkbox. You can then also hook to thechange
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); });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><ulclass="dropdown-menu columnsFilterDropDownMenu"id="columnsListDropDown"><li><labelclass="small"data-value="Type"><inputtype="checkbox"checked=""value="Type"> Type </label></li><li><labelclass="small"data-value="Release"><inputtype="checkbox"checked=""value="Release"> Release </label></li></ul><tableid="myTable"><tr><tddata-column="Type">Type</td><tddata-column="Release">Release</td></tr></table>
Solution 2:
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 inputif ($(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 elementif ($(input).is(':checked')) { $("#myTable").find("[data-column='"+columnName+"']").hide() $(input).prop('checked', false); } else { $("#myTable").find("[data-column='"+columnName+"']").show() $(input).prop('checked', true); } } returnfalse; });
`
Post a Comment for "Checkbox Stays Checked When Clicking On It In A Dropdown"