[英]On page load, if checkbox is checked, show field
So I have the below code that shows/hides fields depending if the checkbox is checked, but I can't seem to figure out when I refresh the page and my sample data on my form that is saved, has the checkmark already checked, why my fields are not showing on page load.所以我有下面的代码显示/隐藏字段,具体取决于是否选中了复选框,但我似乎无法弄清楚何时刷新页面和我保存的表单上的示例数据,已选中复选标记,为什么我的字段未在页面加载时显示。
On page load (With saved data):
- First checkbox checked (Shows nothing)
- Uncheck then check, then it finally shows
How can I make the fields show on page load when the checkbox is checked?选中复选框后,如何在页面加载时显示字段? I've tried calling the DOMContentLoaded but am I doing it correctly?
我试过调用 DOMContentLoaded 但我做对了吗?
Code :代码:
const formWrapperPersonal = document.getElementById('form-wrapper-personal');
var rtk11 = document.getElementById('rtk1');
function rtk1() {
rtk11.addEventListener('change', (e) => {
if (e.target.checked) {
formWrapperPersonal.style.display = ''
} else {
formWrapperPersonal.style.display = 'none'
}
})
}
rtk11.addEventListener('change', rtk1);
document.addEventListener('DOMContentLoaded', rtk1);
rtk1();
You just need to remove the inner event listener as you already have one on the element and the document.您只需要删除内部事件侦听器,因为元素和文档上已经有了一个。
const formWrapperPersonal = document.getElementById('form-wrapper-personal');
var rtk11 = document.getElementById('rtk1');
function rtk1() {
if (rtk11.checked) {
formWrapperPersonal.style.display = ''
} else {
formWrapperPersonal.style.display = 'none'
}
}
rtk11.addEventListener('change', rtk1);
document.addEventListener('DOMContentLoaded', rtk1);
rtk1();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.