0

Hi,

I have a lot of checkboxes, for a bunch of illnesses. e.g. Cancer, Epilepsy, AIDS Hepatitus etc.

I have put checkboxes in to display a field if one of them is ticked, and the Medical user can make notes on the particular case. But.. I cant hide it again if it is unchecked.

This is what I have so far:

HTML

<input name="1" type="checkbox" value="Cancer" onclick="javascript:showtxtarea('textarea1')" /><p>Cancer</p><br />
<textarea class="address" id="textarea1" style="display: none;"></textarea>
<input name="2" type="checkbox" value="Epilepsy" onclick="javascript:showtxtarea('textarea2')" /><p>Epilepsy</p><br />
<textarea class="address" id="textarea2" style="display: none;"></textarea>

etc

The javascript is:

function showtxtarea(id) {
	if (document.getElementById(id).checked == true) {
		document.getElementById(id).style.display = 'none';
	} else {
		document.getElementById(id).style.display = 'block';
	}	
}

It works great for checking a box, but does not work for unchecking. I must be getting the element wrong.. When I check the value of document.getElementById(id).checked it is undefined.. Can anyone help? I am ok at PHP/MySQL but a real newbie with javascript.

3
Contributors
4
Replies
8
Views
6 Years
Discussion Span
Last Post by catherine sea
0

In "if", you need to check whether the checkbox is checked rather than the text area. Try the code below.

function showtxtarea(id) {

	if (document.getElementById("checkbox1").checked == true) {
		document.getElementById(id).style.display = 'none';
	} else {

		document.getElementById(id).style.display = 'block';
	}	
}
<input name="1" type="checkbox" value="Cancer" id="checkbox1" onclick="javascript:showtxtarea('textarea1')" /><p>Cancer</p><br />
<textarea class="address" id="textarea1" style="display: none;"></textarea>

Regards,

0

Awesome thanks so much!

I also had the function options around the wrong way. I didn't realise I was not using the checkbox's ID. It seems javascript relies very heavily on the ID's.

0

A little change to catherine sea code. Think the textarea should be displayed when the checkbox is checked.

function showtxtarea(id) {

	if (document.getElementById("checkbox1").checked == true) {
		document.getElementById(id).style.display = 'block';
	} else {
                   document.getElementById(id).style.display = 'none';
		
	}	
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.