JavaScript自定义Checkbox状态异常:提交后始终显示未选中
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.checkedvalue. - If it’s
0, it sets the green background and updatesdataset.checkedto1. - If it’s
1, it reverts the background and setsdataset.checkedback to0. - Now when you click the Submit button,
submitValueswill read the correct, updated values fromdataset.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

