我有这段代码可以选中/取消选中所有复选框以及选中/取消选中单个复选框。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Persist checkboxes</title>
</head>
<body>
<div>
<label for="checkAll">Check all</label>
<input type="checkbox" id="checkAll">
</div>
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script>
$("#checkAll").on("change", function() {
$(':checkbox').not(this).prop('checked', this.checked);
});
$(":checkbox").on("change", function(){
var checkboxValues = {};
$(":checkbox").each(function(){
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
});
function repopulateCheckboxes(){
var checkboxValues = $.cookie('checkboxValues');
if(checkboxValues){
Object.keys(checkboxValues).forEach(function(element) {
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
$.cookie.json = true;
repopulateCheckboxes();
</script>
我的问题是我想制作一个按钮,该按钮具有清除或取消选中所有复选框的功能。有人可以帮我做吗?谢谢!
最佳答案
点击按钮时调用以下函数:
function uncheckAll(){
$('input[type="checkbox"]:checked').prop('checked',false);
}
function uncheckAll() {
$("input[type='checkbox']:checked").prop("checked", false)
}
$(':button').on('click', uncheckAll)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='button' value="clear" />
纯JS版:
function uncheckAll() {
document.querySelectorAll('input[type="checkbox"]')
.forEach(el => el.checked = false);
}
document.querySelector('button').addEventListener('click', uncheckAll)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' />
<input type='checkbox' checked/>
<button>Clear</button>
关于javascript - 如何制作一个取消选中所有复选框的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22574344/