Javascript Toggle Checkbox to Hide/Show Text

I was working the other day on creating some text that would appear and disappear at the check of a checkbox.  I realized it’s pretty simple to accomplish with a little javascript!  There are a few ways of accomplishing this, but here’s the method I used.

<head>

Insert this bit of script in the head of your document:

<script language="javascript">
function checktoggle() {
var textboxid = document.getElementById('checktoggle');
if (textboxid.innerHTML == "") {textboxid.innerHTML = "here's my text!";}
else {textboxid.innerHTML = "";}
}
</script>

<body>

Then, in the <body> tags of your document create an empty div with an id of “checktoggle” , and a checkbox.  On the checkbox, be sure to add the onclick=”checktoggle()” action so when clicked it will run the above function.:

<div id="checktoggle"></div>
<input onclick="checktoggle()" type="checkbox"/>

That’s it, try it out:

To change the text which displays just modify the “here’s my text!” portion (inside the quotes only) of the javascript which you inserted into the head of your document to read whatever you like.

One Comment on “Javascript Toggle Checkbox to Hide/Show Text” Comments RSS Feed

  1. Rory Carter says:

    Hi,

    I appreciate your code, thank you. Although i want to display a div from my document “document.getElementById”. At the moment if ticked you recieve heres my text, when i add getElementById i recieve an objecterror. Any assistance would be greatly appreciated. Thank You

Leave a Reply