Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

css - 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). 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. Should I put in my css this? :

 #powermail_fieldwrap_331{
 display:none;
 } 

I would highly appreciate any suggestions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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';
};

Demo


If you want to hide it by default, you could use #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();

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...