0

I am trying to create a dropdown after I choose an option in an original dropdown.

This is the HTML code:

<br>
<select id ="select-container" onchange="addSelect('select-container');">
    <option>test1</option>
    <option>test2</option>
    <option>test3</option>
</select>
<br>

This is the javascript.

function categorygenerate() {
    //for testing purposes
    var categoryarray = new Array(),
        i;
    for (i = 0; i < 3; i++) {
        categoryarray[i] = Math.random();
    }
    return categoryarray;
}

function addSelect(divname) {
    var newDiv = document.createElement('div');
    var html = '<select>',
        dates = categorygenerate(),
        i;
    for (i = 0; i < dates.length; i++) {
        html += "<option value='" + dates[i] + "'>" + dates[i] + "</option>";
    }
    html += '</select>';
    newDiv.innerHTML = html;
    document.getElementById(divname).appendChild(newDiv);
    console.log($("#" + divname).html());
    console.log(newDiv);
}

The debugger mode shows me no error.

0

2 Answers 2

2

It is because you are trying to append your code in the "original select": look at the id of your select.

You have to add a div tag with the id="select-container" and remove it from the "original select"

Here is a working snippet:

function categorygenerate() {
    //for testing purposes
    var categoryarray = new Array(),
        i;
    for (i = 0; i < 3; i++) {
        categoryarray[i] = Math.random();
    }
    return categoryarray;
}

function addSelect(divname) {
    var newDiv = document.createElement('div');
    var html = '<select>',
        dates = categorygenerate(),
        i;
    for (i = 0; i < dates.length; i++) {
        html += "<option value='" + dates[i] + "'>" + dates[i] + "</option>";
    }
    html += '</select>';
    newDiv.innerHTML = html;
    document.getElementById(divname).appendChild(newDiv);
    console.log($("#" + divname).html());
    console.log(newDiv);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<select onchange="addSelect('select-container');">
    <option>test1</option>
    <option>test2</option>
    <option>test3</option>
</select>
<br>
<div id="select-container"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

Put your select in a div with the id select-container. Ofcourse, give your select an other ID. Then your code should work. It's because you try to append a new select to the original one in your HTML.

https://jsfiddle.net/b248a4k1/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.