Some webpages have a "turning" triangle control that can collapse submenus. I want the same sort of behavior, but for sections in a form.
Say I had a form that had lender, name, address and city inputs. Some of my site's users are going to need a second set of these fields. I would like to conceal the extra fields for the majority of the users. The ones that need the extra fields should be able to access them with one click. How would I do that?
Ah, I think you mean you want to have collapsible sections on your form.
In short:
Here's a better explanation: How to Create a Collapsible DIV with Javascript and CSS [ Update 2013-01-27 the article is no longer available on the Web, you can refer to the source of this HTML page for an applied example inspired by this article]
Or if you Google search with words like "CSS collapsing sections" or such you will find many other tutorials, including super-fancy ones (eg http://xtractpro.com/articles/Animated-Collapsible-Panel.aspx ).
Your absolute most basic way of hiding/showing an element using JavaScript is by setting the visibility property of an element.
Given your example imagine you had the following form defined on your page:
<form id="form1">
<fieldset id="lenderInfo">
<legend>Primary Lender</legend>
<label for="lenderName">Name</label>
<input id="lenderName" type="text" />
<br />
<label for="lenderAddress">Address</label>
<input id="lenderAddress" type="text" />
</fieldset>
<a href="#" onclick="showElement('secondaryLenderInfo');">Add Lender</a>
<fieldset id="secondaryLenderInfo" style="visibility:hidden;">
<legend>Secondary Lender</legend>
<label for="secondaryLenderName">Name</label>
<input id="secondaryLenderName" type="text" />
<br />
<label for="secondaryLenderAddress">Address</label>
<input id="secondaryLenderAddress" type="text" />
</fieldset>
</form>
There are two things to note here:
showElement()
takes an element id as a parameter and looks like this:
function showElement(strElem) {
var oElem = document.getElementById(strElem);
oElem.style.visibility = "visible";
return false;
}
Almost every JavaScript approach is going to be doing this under the hood, but I would recommend using a framework that hides the implementation details away from you. Take a look at JQuery , and JQuery UI in order to get a much more polished transition when hiding/showing your elements.
Here's a simple css only solution that uses a checkbox:
.hideNext:not(:checked)+div { max-height: 0; overflow: hidden; }
<label for="ch1">More Options</label><input id="ch1" type="checkbox" class="hideNext" /> <div>Whatever you want to hide.</div> and then more stuff below..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.