You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript获取checkbox复选框选中值的实现问题

问题原因

相同name属性的复选框在document.forms接口中会返回DOM节点集合,而非单个表单元素,直接调用.value属性无法批量获取选中项的值,该写法仅适用于单选的radio类型字段。

修正方案

遍历所有name为music的复选框,筛选出checked属性为true的项,收集对应value即可,修改后的JS代码如下:

function writee(){
    // 转成数组兼容单复选框、多复选框场景
    const checkboxes = Array.from(document.forms["formz"].music);
    // 筛选选中项,收集值
    const selectedValues = [];
    for (let item of checkboxes) {
        if (item.checked) {
            selectedValues.push(item.value);
        }
    }
    // 可选:把数组转成顿号分隔的字符串展示
    const x = selectedValues.join('、');
    const oo=window.open(" ","tab","width=300,height=350")
    oo.document.open()
    oo.document.write(x)
}

内容的提问来源于stack exchange,提问作者Amoon3234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:54:05