Prevent appearing from multiple dom elements

Hi,

when user chooses an option in selectbox a new box is triggered.

But supposed user changes his opinion and choose a new option, the former selectbox does not vanish.

How can I make the “wrong” selectbox – first choice – vanish.
I have a working example at codepen to illustrate the issue.

When user makes a decision with “Choose Option” he calls the hotelchecker function, so that a second selectbox appears “Option based on previous choice”. When he than reconsider his choice and choose again from “Choose option” - how can I prevent, that I have multiple second selectboxes?

Here is my HTML:

<div id="selectbox">
        <select class="selectstyled" id="change">
        <option value="0">Choose Option</option>
        <option value="1">Option1</option>
        <option value="2">Option2</option>
     
              </select>
    </div>

Here my JS

let changeUse = document.getElementById("change");

changeUse.addEventListener("change", hotelchecker);

function hotelchecker() {
    if (changeUse.value == 1) {
        document.getElementById("selectbox").insertAdjacentHTML("afterend", `
        <div id = "selectbox">
        <select class = "selectstyled"
        id = "changeHotel">
        <option value="0">Option based on previuos choice</option>
        <option value="1">Further choice 1</option>
        <option value="2">Further choice 2</option>
        <option value="3">Further choice 3</option>
        </select>
        </div>
    `)
           }
    if (changeUse.value == 2) {
    document.getElementById("selectbox").insertAdjacentHTML("afterend", `
        <div id = "selectbox">
        <select class = "selectstyled"
        id = "changeHotel">
       <option value="0">Option based on previuos choice</option>
        <option value="1">Further choice 1</option>
        <option value="2">Further choice 2</option>
        <option value="3">Further choice 3</option>
        </select>
        </div>
       
    `)
    }
};

Danger, Will Robinson… reusing ID’s will cause it not to be selectable by javascript. Look carefully at what happens when you insert that last dropdown - where does it insert it?

The solution is to always remove the previously added content before adding new stuff.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.