The sample code uses JQuery to prevent the user from unchecking the last checked checkbox. It works as expected in Firefox and Chrome, but not in Opera or IE.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#checkboxContainer label {
float: left;
clear: right;
}
#checkboxContainer input {
float: left;
clear: left;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#checkboxContainer input[type='checkbox']").change(function(evt) {
if ($("#checkboxContainer input[type='checkbox']:checked").length == 0) {
console.log("Only 1 checkbox; can't uncheck.");
$(evt.target).attr("checked", "checked");
}
});
});
</script>
</head>
<body>
<div id="checkboxContainer">
<input type="checkbox" id="checkbox1" checked="checked"/>
<label for="checkbox1">1</label>
<input type="checkbox" id="checkbox2"/>
<label for="checkbox2">2</label>
</div>
</body>
</html>
What’s going on here?
This seems to work in IE and Opera if you change your selector to “:checkbox” instead of “input[type=’checkbox’]”. The jQuery docs state that the two are equivalent, so I am not sure how to explain the difference in behavior.