利用 javascript 或是 jQuery 來完成 checkbox 全選的功能
剛剛有同事問,試寫了一下,怕自己健忘筆記一下。
javascript:
<script language="javascript" type="text/javascript">
function checkAll() {
var checkboxes = document.getElementsByName('ck');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = true;
}
}
</script>
jQuery:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#btnSelectAll').click(function() {
$('input:checkbox').each(function() {
this.checked = true;
}
);
});
});
</script>
html:
<div>
<input id="btnSelectAll" type="button" value="全選jQuery" />
<input type="button" value="全選javascript" onclick="checkAll()" />
</div>
<div>
<input name="ck" type="checkbox" />
<input name="ck" type="checkbox" />
<input name="ck" type="checkbox" />
<input name="ck" type="checkbox" />
<input name="ck" type="checkbox" />
</div>
javascript:
<script language="javascript" type="text/javascript">
function checkAll() {
var checkboxes = document.getElementsByName('ck');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = true;
}
}
</script>
jQuery:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#btnSelectAll').click(function() {
$('input:checkbox').each(function() {
this.checked = true;
}
);
});
});
</script>
html:
<div>
<input id="btnSelectAll" type="button" value="全選jQuery" />
<input type="button" value="全選javascript" onclick="checkAll()" />
</div>
<div>
<input name="ck" type="checkbox" />
<input name="ck" type="checkbox" />
<input name="ck" type="checkbox" />
<input name="ck" type="checkbox" />
<input name="ck" type="checkbox" />
</div>
留言