View Full Version : Resolved How to Reset HTML Form drop down list on Page Reload

06-28-2012, 04:05 AM

I've almost got a table swap out feature on my page working (thanks to Old Pedant) but there is one thing that is eluding me. (Page is at http://www.the-house-plans-guide.com/joist-span-tables-with-script.html#joistspancalculator)

If you refresh (reload) the page, the previously stored value of the drop down list is still shown but the default table (which is set to be visible) is displayed. This could result in the wrong table being shown for what is displayed in the drop down.

Could I add an addEventListener("load"...) to somehow reset the dropdown value anytime the page is reloaded? How would I implement this?

I would also need to reset the dropdown value if the user used their browser back (or forward) arrow and then returned to the page as the table is reset in this instance too.

Sorry I know this is probably very basic but I'm just figuring out Javascript after not doing any programming since the days of Pascal (the language not the person!).



Old Pedant
06-28-2012, 04:14 AM
Oh, that's easy. And I would assume you'd like to reset the 4 forms to blank as well?
If so, it would be better if you'd give each of your <form>s a unique name or id.

I'll assume you gave them unique ids (preferable over names) of "joistForm1", "joistForm2", etc.


<script type="text/javascript">
document.getElementById("species").onchange =
function() {
var opts = this.options;
for ( var i = 0; i < opts.length; ++i )
var tblID = opts[i].value;
document.getElementById(tblID).style.display = ( opts[i].selected ? "block" : "none" );
// reset the species choice:
document.getElementById("species").selectedIndex = 0;

// reset all 4 forms:
for ( var fnum = 1; fnum <= 4; ++fnum )
document.getElementById("joistForm" + fnum).reset();

Untested, but I think it should work.

06-28-2012, 05:17 AM
Thank you , thank you! It works like a charm.

I had used unique names for the forms, not ids. I'll have to do some reading to understand the difference between how they are used.


Old Pedant
06-28-2012, 05:36 AM
Names for <form>s have been deprecated for some time now. SO it's better to use ids.

But you *can* use names (and probably will be able to for years to come).

To get a form (or anything) by ID, you use document.getElementById("...id of element...")

To get a form by name, you can simply do document.formName

You can also do document.forms["...formname..."] but I have never seen a reason to do that. If you are going to do that, use an ID instead.