javascript 如何使用 jquery 将新项目动态添加到此表单中的下拉列表中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33978806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:05:23  来源:igfitidea点击:

How do I dynamically add new items to dropdown list within this form using jquery?

javascriptjqueryhtmlforms

提问by NucleusDevelopment

$(document).ready(function() {
    var element;
    $(".form-element").on("mousedown", function(event){
    element = $('<form><select name="dropdown"><option>Select...</option><option value="new-dropdown">add new...</option><option value="machine3">Machine 3</option><option value="machine4">Machine 4</option></select></form>');
    $("#body-div").append(element);
    });
});

The items in the list currently are just there for testing. But I need to be able to click on an add new option and add a new list item.

列表中的项目目前仅用于测试。但我需要能够单击添加新选项并添加新列表项。

回答by adriancarriger

Working Fiddle

工作小提琴

It looks like you were trying to dynamically add the entire form, but you only need to add additional optionelements to your selectsection of your form.

看起来您正在尝试动态添加整个表单,但您只需要向表单optionselect部分添加其他元素。

To do this add this HTML

为此,请添加此 HTML

HTML

HTML

<input id="text-to-add" type="text" value="Machine 3">
<button id="new-item">Add to dropdown</button>
 <form>
     <select name="dropdown">
         <option>Select...</option>
         <option>Machine 1</option>
         <option>Machine 2</option>
     </select>
</form>

Then to dynamically add a select element use the append jQueryfunction.

然后使用append jQuery函数动态添加选择元素。

jQuery

jQuery

$(document).ready(function () {
    $('#new-item').click(function() {
        console.log($('#text-to-add').val());
        $('select').append( '<option>' + $('#text-to-add').val() + '</option>' );
    });
});

回答by Shrikanth Buds

First add a new id for both the select tag and the option tag with the value "new option";

首先为select标签和option标签添加一个新的id,值为“new option”;

element = $('<form>
<select name="dropdown" 
id="sel"><option>Select...</option>
<option value=
"new-dropdown"id="anew">add new...
</option></select></form>');

now im assuming that you already have the values for both the value and the text for that option let both of them be x and y respectively; now add an onClick handler to #anew to append #sel with a new option with value x and text y:

现在我假设您已经拥有该选项的值和文本的值,让它们分别为 x 和 y;现在将一个 onClick 处理程序添加到 #anew 以将带有值 x 和文本 y 的新选项附加到 #sel 中:

z=$('<option value="'+x+'">'+y+'</option>');

$("#anew").onClick(function(){
$("#sel").append(z);
});

hope it solves your problem

希望它能解决你的问题