[英]javascript Hide/show div on checkbox: checked/unchecked
I am trying to make a function in javascript, that will hide / show particular div in my registration form, depending on the state of my checkbox (checked or not). 我试图在javascript中创建一个函数,这将隐藏/显示我的注册表单中的特定div,具体取决于我的复选框的状态(已选中或未选中)。 Here is my function: 这是我的功能:
function doruc() {
var elem = document.getElementById('powermail_fieldwrap_331');
if (document.getElementById ('powermail_field_doruovaciaadresa2_1').checked) {
elem.display='block';
} else {elem.display:none;}
}
It isnt working. 它不起作用。 I am checking and unchecking my checkbox, but nothing happens. 我正在检查并取消选中我的复选框,但没有任何反应。 Oh and one more thing. 还有件事儿。 I want that div to be initialized as hidden. 我希望将div初始化为隐藏。 Should I put in my css this? 我应该把这个放进我的CSS吗? : :
#powermail_fieldwrap_331{
display:none;
}
I would highly appreciate any suggestions. 我非常感谢任何建议。
You could use 你可以用
var elem = document.getElementById('powermail_fieldwrap_331');
document.getElementById('powermail_field_doruovaciaadresa2_1').onchange = function() {
elem.style.display = this.checked ? 'block' : 'none';
};
If you want to hide it by default, you could use #powermail_fieldwrap_331{display:none;}
. 如果要在默认情况下隐藏它,可以使用#powermail_fieldwrap_331{display:none;}
。 But if you want to be sure, better use 但如果你想确定,更好地使用
var elem = document.getElementById('powermail_fieldwrap_331'),
checkBox = document.getElementById('powermail_field_doruovaciaadresa2_1');
checkBox.checked = false;
checkBox.onchange = function doruc() {
elem.style.display = this.checked ? 'block' : 'none';
};
checkBox.onchange();
试试这个:
elem.style.display='block'
You should write it like this : 你应该这样写:
function doruc() {
var elem = document.getElementById('powermail_fieldwrap_331');
if (document.getElementById ('powermail_field_doruovaciaadresa2_1').checked) {
elem.style.display='block';
} else {elem.style.display='none';}}
and regarding your second question, you can either write in the div tag style="display:none"
or you can do as you said (add a class for the element). 关于你的第二个问题,你可以写div标签style="display:none"
或者你可以像你说的那样(为元素添加一个类)。
You are correct in using display: none; 你正确使用display:none; to hide your DIV initially. 最初隐藏你的DIV。
As for your checkbox, try removing the spaces between getELementById and ('powermail_field... 至于你的复选框,请尝试删除getELementById和('powermail_field ...之间的空格)
Also you need to change: 你还需要改变:
} else {elem.display:none;}
to: 至:
} else {elem.display = 'none';}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.