TechQuest: Welcome to TechQuest.
Simple JavaScript: Add/Hide Html Elements
No users have rated this item yet.

One of the easiest JavaScript tricks to do is to show and hide elements of a page or web form based on user input or data.

I have a form that is used for submitting items for this web site. Among other things, this form allows me to upload images that are incorporated into the article. Sometimes I don't want any items and sometimes I want several. It would be nice to make it flexible so that I can even add an unlimited number of images in the post. At first, I made a form with three fields for image uploads. If I don't enter anything into them, leave them blank, the article won't include any images (as you might expect). The DavesWeb server software is able to accomodate this and process accordingly. Then, of course, the day came when I wanted four images with the article. Maybe someday, I'd want ten. I added more fields for a total of ten image upload fields, but that wasn't very elegant, was it?
Uploaded Image

Seems like a cleaner design might not display an "Image: Choose File" field at all, but begin with an "Add Image" button.
Uploaded Image

Click the "Add Image" button and an "Image: Choose File" field is now displayed. Click it again and you see another one, and so on as needed.
Uploaded Image
This feels much cleaner.

The code is not complicated. In this example, you can add a maximum of three images to the post. Each Html input tag has a distinct but consistent ID.
Uploaded Image
Below the input tags for the images is the tag for the "Add Image" button. When clicked, the AddImageRow() function is called. AddImageRow checks the three input fields to see which is the last one hidden, and shows it. For good measure, if the function has displayed all three input fields available, and there's no point in trying to add another one, it hides the "Add Image" button.
Uploaded Image
Note that this JavaScript block doesn't have to reside in the head section of your page.

There's a working demo here

5,048 views.
No users have rated this item yet.