Dynamically add input type select with options in Javascript

前端 未结 2 791
青春惊慌失措
青春惊慌失措 2020-12-09 12:21

I have found adding inputs to a form is quite simple in Javascript, but for some reason adding the select input with options is not working. The options are appearing outsid

相关标签:
2条回答
  • 2020-12-09 12:53

    Pure Vanila JS

    var choices = ["one", "two"];
    
    function addInput(divName) {
        var newDiv = document.createElement('div');
        var selectHTML = "";
        selectHTML="<select>";
        for(i = 0; i < choices.length; i = i + 1) {
            selectHTML += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";
        }
        selectHTML += "</select>";
        newDiv.innerHTML = selectHTML;
        document.getElementById(divName).appendChild(newDiv);
    }
    <form class="new" method="post" action="/jobs">
        <div id="dynamicInput"></div>
        <input type="button" value="Add" onclick="addInput('dynamicInput');" />
        <input type="button" value="Save" />
    </form>


    jQuery Version

    var choices = ["one", "two"];
    
    function addInput(divName) {
        var select = $("<select/>")
        $.each(choices, function(a, b) {
            select.append($("<option/>").attr("value", b).text(b));
        });
        $("#" + divName).append(select);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <form class="new" method="post" action="/jobs">
        <div id="dynamicInput"></div>
        <input type="button" value="Add" onclick="addInput('dynamicInput');" />
        <input type="button" value="Save" />
    </form>

    0 讨论(0)
  • 2020-12-09 12:59

    Each time you set the innerHTML property, your browser will create DOM elements of what you inserted.

    When you added <select> to the innerHTML, your browser most likely added </select> to make it valid html.

    Then when you retrieved it to add the options, it came back as <select></select>.

    Try building the whole html string to insert in a normal variable and inserting it just once.

    0 讨论(0)
提交回复
热议问题