4

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.

user2886091
  • 725
  • 7
  • 16
  • 29

4 Answers4

7

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

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Thank you. It works. Could you please explain it to me? What was wrong on my function and so on? – user2886091 Nov 01 '13 at 20:50
  • @user2886091 You code didn't work because you should have used `elem.style.display='block'` instead of `elem.display='block'`, and `elem.style.display='none'` instead of `elem.display:none`. Moreover, you need to run that code each time the checkbox is changed, so you need to listen to `change` event (assuming you weren't using `checkBox.onchange = doruc` in your code) – Oriol Nov 01 '13 at 20:54
1

Try this:

elem.style.display='block'
karaxuna
  • 26,752
  • 13
  • 82
  • 117
0

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).

lior y
  • 104
  • 7
0

You are correct in using display: none; to hide your DIV initially.

As for your checkbox, try removing the spaces between getELementById and ('powermail_field...

Also you need to change:

} else {elem.display:none;}

to:

} else {elem.display = 'none';}
Rob Gibbons
  • 1,583
  • 3
  • 14
  • 24