萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET JavaScript 取得 CheckBoxList 選取值並以分隔符號合併

前端結構

<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>

JavaScript 核心邏輯

<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>

後端綁定 CheckBoxList (Page_Load)

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 + 彈出層。

copyright © 萬盛學電腦網 all rights reserved