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

JavaScript自定义Checkbox状态异常:提交后始终显示未选中

Why Your Custom Checkbox State Isn't Updating Correctly

Let’s walk through what’s going wrong here and fix it:

The root issue is in your toggleCB function. Take a look at this line:

cb.style.checked = 1;

You’re trying to update the checkbox’s checked state by setting a checked property on the element’s style object—but the style object only controls CSS styles, not your custom data-checked attribute. This line does nothing to change the actual value that your submitValues function reads (dataset.checked).

Since you never update dataset.checked when setting the green background, the value stays stuck at 0 forever. That’s why your alert always shows cb1 = 0 cb2 = 0, even after clicking the checkboxes.

Fixing the Code

Just replace the incorrect cb.style.checked = 1; line with cb.dataset.checked = 1; to properly update the custom data attribute:

function toggleCB(cb){ 
  if(cb.dataset.checked == 0){ 
    cb.style.background = "#89D814"; 
    cb.dataset.checked = 1; // This line was fixed
  }else{ 
    cb.style.background = "#EEE"; 
    cb.dataset.checked = 0; 
  } 
}

How It Works Now

  • When you click a checkbox, the function checks the current dataset.checked value.
  • If it’s 0, it sets the green background and updates dataset.checked to 1.
  • If it’s 1, it reverts the background and sets dataset.checked back to 0.
  • Now when you click the Submit button, submitValues will read the correct, updated values from dataset.checked.

Bonus: A Small Cleanup Tip

For slightly cleaner logic, you could use boolean values (true/false) instead of 0/1, but your current approach works perfectly once the typo is fixed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:05:25