简体   繁体   English

Javascript:使用按钮动态添加选择输入中的字段

[英]Javascript: Dynamically add fields from a select input with a button

i need to add dynamically fields from a list values, i have this one: 我需要从列表值中动态添加字段,我有这个:

HTML: HTML:

<select name="list">
    <option>Select One</option>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">D</option>
</select>

JS: JS:

$("[name=list]").on("change", function (e) {
    var val = $(this).val();
    if (val.length > 0) {
        $("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
    }
});

This works fine, but i want to add a "Add field" button to do this, how i can do that? 这工作正常,但我想添加一个“添加字段”按钮来执行此操作,我该怎么做?

Its just simple. 这很简单。 Instead of writing your code into onchange , you bind it to click event of your button . 无需将代码编写为onchange ,而是将其绑定到button click event

For example, say you have button with id - #addField . 例如,假设您有一个id - #addField button Your click event for button would be 您的button click event

$("#addField").on('click',function(){
    var val = $("[name=list]").val(); //get the selected val from select element
    if (val.length) {
        $("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
    }
});

You will move the logic of the .change() event of select to the .click() event of the button. 您将在逻辑移动.change()的select事件到.click()按钮的事件。

something similar to: 类似于:

$("#btnId").on("click", function (e) {
    var val = $("[name=list]").val();
    if (val.length > 0) {
        $("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
    }
});

where btnId is the id of the button 其中btnId是按钮的id

try this : https://jsfiddle.net/qact415y/ 试试这个: https : //jsfiddle.net/qact415y/

<select id="list">
<option>Select One</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>

// enter the text you want to add to the combo
<input type="text" id="input"/>
<button name="add">Add</button>


$("[name=list]").on("change", function (e) {
    var val = $(this).val();
    if (val.length > 0) {
        $("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
    }
});

$("[name=add]").on("click", function (e) {
        console.log("add");
    var x = document.getElementById("list");
    var option = document.createElement("option");
    option.text = document.getElementById("input").value;
    x.add(option);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM