How to choose and work with a drop down list in js

This line:

} else if (dropDownList.selectedIndex = 1) {

needs to use a comparison equals operator rather than an assignment equals operator:

} else if (dropDownList.selectedIndex === 1) {

The other if/else clauses are similarly incorrect.

I highly recommend using a decent IDE, it would highlight potential mistakes like this for you.

You will also need to change this:

document.getElementById('form').innerHTML = formArray[dropDownList.selectedIndex];

to this:

document.getElementById('form').innerHTML = formArray[dropDownList.selectedIndex - 1];

The selectedIndex is live, if you change it using -- that will cause the selected value to be updated.

The way the result is output assumes there is an <h3> with the id resultField but only one of your forms has that id set.

Other miscellaneous suggestions include…

The id attributes need to be unique throughout the document. You currently have 3 hidden forms and you copy around the HTML, leading to 4 elements with each id (resultField, fieldx, fieldy). Whether document.getElementById grabs the right one is down to luck.

Rather than copying around the innerHTML of those forms you’d be better off simply showing and hiding the existing forms using CSS. Alternatively you could use just 1 form and update the relevant text to match the current algorithm.

Listening for the submit event of the form seems odd. Why not use a regular button and listen for the click event?

If you do decide to keep the 3 forms I would suggest registering separate button handlers for each one. The fact that so much of your code is inside a big if/else is a sign that you actually need multiple functions rather than a single function that has to figure out which mode it is in. The code they share could be factored out if appropriate.

Browse More Popular Posts

Leave a Comment