使用jQuery向下拉列表中添加选项的最简单方法是什么?

这行吗?

$("#mySelect").append('<option value=1>My option</option>');

当前回答

如果要在选择中的特定索引处插入新选项:

$("#my_select option").eq(2).before($('<option>', {
    value: 'New Item',
    text: 'New Item'
}));

这将在选择中插入“新项目”作为第三个项目。

其他回答

如果要在选择中的特定索引处插入新选项:

$("#my_select option").eq(2).before($('<option>', {
    value: 'New Item',
    text: 'New Item'
}));

这将在选择中插入“新项目”作为第三个项目。

可以使用文本附加和设置“值”属性:

$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));

答案中没有提及,但很有用。如果您希望也选择该选项,您可以添加:

var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);

当您附加选项并使用jqueryvalidate时,我们发现了一些问题。您必须在选择多个列表中单击一个项目。您将添加此代码以处理:

$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");

$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected

$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected

我就是这样做的,用一个按钮添加每个选择标记。

$(document).on("click","#button",function() {
   $('#id_table_AddTransactions').append('<option></option>')
}