Toggle visibility of a form field with a checkbox

by Arthur
Posted on Monday, January 23rd, 2006 at 8:18 pm CET
This example shows how to use a checkbox to toggle the visibility of another form element. This can be useful if you want to hide certain options in a form until the checkbox has been checked.
The Javascript in this example uses a simple function named toggle to switches the display style of a span element to ‘none’ (hidden) or ” (visible). The name of the element is passed as a variable thiselement with the function:
function toggle(thiselement)
{
if (document.getElementById(thiselement).style.display=='none' )
{ document.getElementById(thiselement).style.display = ''; }
else
{ document.getElementById(thiselement).style.display = 'none'; }
}
And here is the HTML code that displays the form. Note that the checkbox has an onClick even that calls the Javascript function toggle specified above. In the function the element apples is passed, which corresponds to the id of the span. The display style of the span apples is set to none (invisibile) by default. The Javascript function changes this when the checkbox is checked.
And here is the end result:
This example shows how to use a checkbox to toggle the visibility of another form element. This can be useful if you want to hide certain options in a form until the checkbox has been checked.
The Javascript in this example uses a simple function named toggle to switches the display style of a span element to ‘none’ (hidden) or ” (visible). The name of the element is passed as a variable thiselement with the function:
function toggle(thiselement)
{
if (document.getElementById(thiselement).style.display=='none' )
{ document.getElementById(thiselement).style.display = ''; }
else
{ document.getElementById(thiselement).style.display = 'none'; }
}
And here is the HTML code that displays the form. Note that the checkbox has an onClick even that calls the Javascript function toggle specified above. In the function the element apples is passed, which corresponds to the id of the span. The display style of the span apples is set to none (invisibile) by default. The Javascript function changes this when the checkbox is checked.
And here is the end result:




















