Easy bulk changes with DHTML

By | | JavaScript

4

Andy Clarke has published a neat new technique called Trimming form fields, which uses beautiful unobtrusive DHTML to allow users to toggle the visibility of optional form fields for easier completion of forms. Andy’s code is very tidy and you should go and read his tutorial, because I’m about to extend on it.

Andy’s code works by cycling through each div on the page, looking for those with class fm-optional and toggling their display value. This works just fine, but there’s actually a more effective way of achieving the same effect. Instead of toggling a whole bunch of individual elements, change the class on an element that contains all of those that you wish to toggle and use a simple CSS selector to target the contained elements.

I’ve demonstrated this alternative technique on this page (adapted from Andy’s example). Here’s the CSS:


form.remove div.fm-optional {
display: none;
}

And the link event handler:


toggle.onclick = function() {
if (/remove/i.exec(this.firstChild.nodeValue)) {
this.firstChild.nodeValue = 'Display optional fields?';
document.getElementById('example-form').className = 'remove';
} else {
this.firstChild.nodeValue = 'Remove optional fields?';
document.getElementById('example-form').className = 'display';
}
return false;
}

The above code could certainly be improved – for example, it doesn’t deal with the possibility of the form having one or more existing classes that need to be maintained. It serves as a useful demonstration of how bulk changes can be made to a document by switching just a single class on a containing element.

The Ultimate JavaScript Bundle: 2 books + 1 course

Buy now $39 Normally $117 - save 66%

Or get access to all SitePoint's Premium Content with a Learnable membership

{ 4 comments }

Joel Farris August 6, 2006 at 4:02 pm

I like this idea, but could it be modified to work as a toggle for an either/or scenario?

Let’s say I need to have a radio group that switches back and forth between personal or company fields. All the name, address, phone stuff stays the same, but the personal job description dropdown has different things in it than the company job description dropdown. Also, there is no reason to show a Company field if the person filling in the subscription form doesn’t work for a company.

So instead of toggling the non-required form fields, could it be adapted to work on a radio group?

Andy Budd July 23, 2004 at 12:32 pm

Very slick. There’s some lateral thinking for you

thoms July 8, 2004 at 6:34 pm

I wasn’t aware of this pattern matching function in javascript, maybe it could be a nice blog entry :)

ant1832 July 8, 2004 at 2:54 pm

Wow, what luck. I’m about to start on a project that required me to come up with a way to do this. Thanks for posting it!

Comments on this entry are closed.