Log in

View Full Version : Dynamically hide/show portion of HTML when checkbox is selected



fred2028
01-21-2011, 06:53 PM
I need to be able to dynamically show part of HTML when a checkbox is selected, and hide it again when the checkbox is deselected. This part of HTML will contain form elements and anything entered in them need to be cleared when the checkbox is deselected. How can I do this?

djr33
01-21-2011, 10:40 PM
Create a form with an id of "myform" (at least that is for this example). And create a div with an id of "myhide".


//show the div:
document.getElementById('myhide').style.display = "block";

//hide the div:
document.getElementById('myhide').style.display = "none";

//clear the form:
document.getElementById('myform').reset();

Of course you will need to apply those in the right locations. If you're using a checkbox, then you can apply the code using onchange="showhide();"

Here's the function for showhide(). Place this in your head section.

<script type="text/Javascript">
function showhide() {
if (document.getElementyById('myhide').style.display = "none") {
//show the div:
document.getElementById('myhide').style.display = "block";
}
else {
//hide the div:
document.getElementById('myhide').style.display = "none";
//clear the form:
document.getElementById('myform').reset();
}
}
</script>

Nile
01-21-2011, 10:48 PM
Similarly:


<!DOCTYPE html>
<html>
<head>
<title>Checkbox</title>
<script type="text/javascript">
var checkDisplay = function(check, form) { //check ID, form ID
form = document.getElementById(form), check = document.getElementById(check);
check.onclick = function(){
form.style.display = (this.checked) ? "block" : "none";
form.reset();
};
check.onclick();
};
</script>
</head>
<body>
<input type="checkbox" id="check" />
<form id="form">
<input type="checkbox" /><input type="text" />
</form>
<script type="text/javascript">
checkDisplay("check", "form");
</script>
</body>
</html>