<asp:TextBox ID="txtKeyWords" runat="server" ReadOnly="true" CssClass="inp" />
<input type="button" id="btnSelect" value="選擇" onclick="locking(this)" class="tailBut" />
<div id="keyWordsDiv" style="display:none; position:absolute; border:2px solid #6FA1D9; background:#EAF1FD; width:260px; height:120px; z-index:3;">
<div style="background:#6FA1D9; height:20px; cursor:pointer;">
<ul style="line-height:20px;">
<li style="float:right" onclick="getCheckValue()">[確定]</li>
<li style="float:right" onclick="closeSelf()">[關閉]</li>
</ul>
</div>
<div>
<asp:CheckBoxList ID="cblKeyWords" runat="server" RepeatColumns="2" />
</div>
</div>
<script>
// 定位並顯示彈出層
function locking(btn) {
var left = 0, top = 0, el = btn;
while (el) { left += el.offsetLeft; top += el.offsetTop; el = el.offsetParent; }
var div = document.getElementById("keyWordsDiv");
div.style.left = left + "px";
div.style.top = (top + 20) + "px";
div.style.display = "block";
}
// 關閉並重置
function closeSelf() {
var div = document.getElementById("keyWordsDiv");
div.style.display = "none";
var inputs = div.querySelectorAll("input[type=checkbox]");
inputs.forEach(cb => cb.checked = false);
}
// 取得選取值並寫入 TextBox
function getCheckValue() {
var cbl = document.getElementById("<%= cblKeyWords.ClientID %>");
var checkboxes = cbl.querySelectorAll("input[type=checkbox]");
var labels = cbl.querySelectorAll("label");
var values = [];
checkboxes.forEach((cb, i) => {
if (cb.checked) {
// 找對應 label (for 屬性 = checkbox id)
var lbl = Array.from(labels).find(l => l.htmlFor === cb.id);
if (lbl) values.push(lbl.innerText);
}
});
document.getElementById("<%= txtKeyWords.ClientID %>").value = values.join("|");
closeSelf();
}
</script>
if (!IsPostBack)
{
cblKeyWords.DataSource = GetKeywords(); // 回傳 List>
cblKeyWords.DataTextField = "Value";
cblKeyWords.DataValueField = "Key";
cblKeyWords.DataBind();
}
ClientID 確保 JS 找到正確控制項 (特別在 Master Page/命名容器中)。label[for=checkboxId] 關聯取得顯示文字,避免依賴 nextSibling 等脆弱結構。join("|") 產生分隔字串,比字串累加效能佳且程式碼簡潔。offsetParent 累加,相容巢狀容器。建議改用 Select2、Choices.js 或 Bootstrap Multiselect 等前端元件,支援搜尋、標籤化、單/多選切換,體驗遠優於 CheckBoxList + 彈出層。