網路上全選與賦值的方法很多,但符合特定需求的卻不好找。以下分享一個實作:點擊「全選」按鈕後,把所有核取方塊的值拼接起來,填入指定的文字框,再次點擊則取消全選並清空。
<script>
function uncheckAll() {
var code_Values = document.getElementsByName('email');
var tem = document.getElementById("to").value;
var bb = document.getElementById('to');
if (code_Values.length) {
for (var i = 0; i < code_Values.length; i++) {
if (code_Values[i].checked) {
code_Values[i].checked = false;
tem = tem.replace(code_Values[i].value + ",", "");
} else {
code_Values[i].checked = true;
tem += code_Values[i].value + ",";
}
}
}
bb.value = tem;
}
</script>
<input id="to" type="text" class="input" size="60" name="to" value="" />
<input type="button" class="btn" onclick="javascript:uncheckAll();" value="全選" />
<input type="checkbox" value="111" name="email" /> 111
<input type="checkbox" value="222" name="email" /> 222
<input type="checkbox" value="333" name="email" /> 333
函式先取得所有 name 為 email 的核取方塊與目標文字框,接著逐一檢查:若某項已勾選就取消並從字串中移除對應值;若未勾選則勾選並把值附加到字串尾端。最後把彙整好的字串寫回文字框。透過這個「勾選/取消」切換的設計,一顆按鈕就能同時處理全選與清空兩種行為,應用在郵件寄送、群組選取等場景都很方便。