Select "Other" to show input - custom code not working

Hi guys,

I have a Select. When you choose “Other” I need an input field below Select to show up.

I created a component with a form. When I use the code on page no. 1 Select is working fine. When I paste the same code into page no. 2 with the same component, it is not working. Any idea?

Links to the pages I mentioned above:

  1. Registration Forms
  2. Testowy program

Code I use on both pages:

<script>
        document.addEventListener("DOMContentLoaded", function() {
            var selectElement = document.getElementById("Select");
            var otherInputDiv = document.getElementById("otherInput");

            selectElement.addEventListener("change", function() {
                if (this.value === "Other") {
                    otherInputDiv.style.display = "block";
                } else {
                    otherInputDiv.style.display = "none";
                }
            });
        });
    </script>

Here is my site Read-Only: LINK

Hi Maciej,

You have multiple copies of your select in your page. When you use getElementByID, it will only return the first one.

image

This is weird. I was sure I have different id for each Select.

OK I changed them but still showing Other input is not working. I see that code on template page is “invisible”. No reaction for the Select.

There are some consol.logs on one page when I change the value:

No reaction on console.log on the second page:

Awesome. You’ll need to fix otherInput as well

Changed.

But the problem is that the browser does not recognize my code. The console doesn’t record my selection on Select element.

When you have duplicate ID’s like selectPosition, the JS cannot bind to the correct element.
The browser usually chooses the first one, which probably isn’t the one you’re trying to change.

image

I haven’t unpacked your project to try to figure out why you have multiple duplicate form fields here, but somehow you have 3 copies of the registration form, and 2 are hidden?

image

A quick guess would be a component contains a form, and you have 3 instances of the component on your page? Whatever it is, you’ll need to fix your design approach so that the duplicate ID’s problem is fixed.

1 Like

Good point @memetican I had 2 other components with this form hidden on the page. Now form is working fine. Thank you for your clues.