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.

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,

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.

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

haha thanks for correcting.

I'm not so good at Javascript either. Glad I could help.

Regards,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.