Adding a dropdown input box by clicking a plus but

2019-09-06 16:39发布

i am trying to add a box with predefined values in it by clicking a plus button with a variable number in it to define the max addition of new boxes.

Native language:<br>
            <select name="nativelang" id="nativelangdrop">
                <?php
                    if ($file = @fopen('txt/languages.txt', 'r')) {
                    while(($line = fgets($file)) !== false) {
                    echo "<option>{$line}</option>";
                    }
                    fclose($file);
                    }
                ?>
            </select>

i have this in my html file and i want, if a user selects a language, that the user has the oportunity to click a "plus button/ link" to add one more of the same box. I also want to limit the amount of addable selects to a variable number that i can change if needed.

i have found some similar examples here but i dont know any jquery and am not sure how to call this process, so i hope you guys can help me out.

kinda like this in pseudo code:

on.click -> add.item(select);
    if item.number = or > 5 -> add.item = false;

Thanks in advance!

1条回答
你好瞎i
2楼-- · 2019-09-06 16:59

You need to clone the existing select and then append those to a container, keeping a count. You can use the number of options in the original select to restrict the number of new ones. Also, importantly you have to make sure that you give a unique id to each new select you create.

Something on the lines of this:

var total;

// To auto limit based on the number of options
// total = $("#nativelangdrop").find("option").length - 1;

// Hard code a limit
total = 5;


$("#addBtn").on("click", function() {
    var ctr = $("#additional").find(".extra").length;
    if (ctr < total) {
        var $ddl = $("#nativelangdrop").clone();
        $ddl.attr("id", "ddl" + ctr);
        $ddl.addClass("extra");
        $("#additional").append($ddl);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="nativelangdrop">
    <option value="1">Language 1</option>
    <option value="2">Language 2</option>
    <option value="3">Language 3</option>
    <option value="4">Language 4</option>
</select>
<span id="additional"></span>
<hr />
<input id="addBtn" type="button" value=" + " />

查看更多
登录 后发表回答