使用jQuery为添加选项?

时间:2022-11-13 17:54:40

What's the easiest way to add an option to a dropdown using jQuery?

使用jQuery向下拉菜单添加选项最简单的方式是什么?

Will this work?

这工作吗?

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

24 个解决方案

#1


620  

Personally, I prefer this syntax for appending options:

就个人而言,我更喜欢这种附加选项的语法:

$('#mySelect').append($('<option>', {
    value: 1,
    text: 'My option'
}));

If you're adding options from a collection of items, you can do the following:

如果您正在从一个项目集合中添加选项,您可以执行以下操作:

$.each(items, function (i, item) {
    $('#mySelect').append($('<option>', { 
        value: item.value,
        text : item.text 
    }));
});

#2


139  

I agree Ashish, this did NOT work in IE8 (yet did in FF):

我同意Ashish,这在IE8中并没有起作用(但在FF中):

$("#selectList").append(new Option("option text", "value"));

This DID work:

这做的工作:

var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);

#3


69  

You can add option using following syntax, Also you can visit to way handle option in jQuery for more details.

您可以使用以下语法添加选项,也可以访问jQuery中的way handle选项以获得更多细节。

  1. $('#select').append($('<option>', {value:1, text:'One'}));

    $(" #选择”)。追加($(' <选项> ',{价值:1、文本:‘一个’}));

  2. $('#select').append('<option value="1">One</option>');

    $(" #选择”)。追加(“ <选项值= " 1> < /选项>“);

  3. var option = new Option(text, value); $('#select').append($(option));

    var选项=新选项(文本、值);$(" #选择“).append($(选项);

#4


40  

If the option name or value is dynamic, you won't want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:

如果选项名或值是动态的,您就不需要担心在其中转义特殊字符;在这一点上,您可能更喜欢简单的DOM方法:

var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');

#5


32  

Option 1-

You can try this-

你可以试试这个

$('#selectID').append($('<option>',
 {
    value: value_variable,
    text : text_variable
}));

Like this-

像这样,

for (i = 0; i < 10; i++)
{ 
     $('#mySelect').append($('<option>',
     {
        value: i,
        text : "Option "+i 
    }));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id='mySelect'></select>

Option 2-

Or try this-

或者试试这个

$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );

Like this-

像这样,

for (i = 0; i < 10; i++)
{ 
     $('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id='mySelect'></select>

#6


16  

That works well.

这工作得很好。

If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.

如果添加多个选项元素,我建议您一次执行append,而不是在每个元素上执行追加操作。

#7


16  

for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+

无论出于什么原因做$(“#myselect”)。追加(新选项(“文本”、“文本”));在IE7+中不适合我。

I had to use $("#myselect").html("<option value='text'>text</option>");

我必须使用$(“#myselect”)。html(“ <选项值= '文本'> 文本< /选项> ");

#8


13  

To help performance you should try to only alter the DOM once, even more so if you are adding many options.

为了帮助性能,您应该尝试只修改DOM一次,如果您添加了许多选项,那么就更应该这样做。

var html = '';

for (var i = 0, len = data.length; i < len; ++i) {
    html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}           

$('#select').append(html);

#9


12  

I like to use non jquery approach:

我喜欢使用非jquery方法:

mySelect.add(new Option('My option', 1));

#10


10  

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

#11


9  

You can add options dynamically into dropdown as shown in below example. Here in this example I have taken array data and binded those array value to dropdown as shown in output screenshot

您可以动态地添加选项,如下面的示例所示。在本例中,我使用了数组数据,并将这些数组值绑定到下拉,如输出屏幕截图所示。

Output:

输出:

使用jQuery为添加选项?

var resultData=["Mumbai","Delhi","Chennai","Goa"]
$(document).ready(function(){
   var myselect = $('<select>');
     $.each(resultData, function(index, key) {
	     myselect.append( $('<option></option>').val(key).html(key) );
       });
      $('#selectCity').append(myselect.html());
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>

<select  id="selectCity">

</select>

#12


8  

var select = $('#myselect');
var newOptions = {
                'red' : 'Red',
                'blue' : 'Blue',
                'green' : 'Green',
                'yellow' : 'Yellow'
            };
$('option', select).remove();
$.each(newOptions, function(text, key) {
    var option = new Option(key, text);
    select.append($(option));
});

#13


7  

Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:

在任何答案中都没有提到,但有用的是你想要那个选项也被选中,你可以添加:

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

#14


7  

This very simple things. You can do this by this way

这个非常简单的事情。你可以这样做。

$('#select_id').append('<option value="five" selected="selected">Five</option>');

or

$('#select_id').append($('<option>', {
                    value: 1,
                    text: 'One'
                }));

Here is the full guide

这是完整的指南。

#15


4  

There are two ways. You can use either of these two.

有两种方法。你可以用这两个中的任意一个。

First:

第一:

$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');

Second:

第二:

$.each(dataCollecton, function(val, text) {            
    options.append($('<option></option>').val(text.route).html(text.route));
});

#16


3  

You can append and set the Value attribute with text:

您可以使用文本添加和设置值属性:

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

#17


3  

We found some problem when you append option and use jquery validate. You must click one item in select multiple list. You will add this code to handle:

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

$("#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

使用jQuery为添加选项?

#18


2  

If you want to insert the new option at a specific index in the select:

如果您想在select的特定索引中插入新选项:

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

This will insert the "New Item" as the 3rd item in the select.

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

#19


2  

This is just a quick points for best performance

这仅仅是最佳性能的一个快速点。

always when you are dealing with many options, build a big string and then add it to the 'select' for best performance

在处理许多选项时,要构建一个大字符串,然后将其添加到“select”中以获得最佳性能。

f.g.

f.g。

var $mySelect = $('#mySelect'); var str = '';

var mySelect =美元(“# mySelect”);var str = ";

$.each(items, function (i, item) {
    // IMPORTANT: no selectors inside the loop (for the best performance)
    str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string

$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');

Even faster

var str = ""; 
for(var i; i = 0; i < arr.length; i++){
    str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}    
$mySelect.html(str);
$mySelect.multiSelect('refresh');

#20


1  

if u have optgroup inside select, u got error in DOM.

如果在select中有optgroup,则在DOM中出错。

I think a best way:

我认为最好的方法是:

$("#select option:last").after($('<option value="1">my option</option>'));

#21


1  

U can try below code to append to option

你可以试试下面的代码来添加选项。

  <select id="mySelect"></select>

    <script>
          $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
    </script>

#22


1  

$('#select_id').append($('<option>',{ value: v, text: t }));

#23


1  

This is the way i did it, with a button to add each select tag.

这是我的方法,用一个按钮来添加每个选择标签。

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

#24


1  

How about this

这个怎么样

var numbers = [1, 2, 3, 4, 5];
var option = '';

for (var i=0;i<numbers.length;i++){
     option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
    }

    $('#items').append(option);

#1


620  

Personally, I prefer this syntax for appending options:

就个人而言,我更喜欢这种附加选项的语法:

$('#mySelect').append($('<option>', {
    value: 1,
    text: 'My option'
}));

If you're adding options from a collection of items, you can do the following:

如果您正在从一个项目集合中添加选项,您可以执行以下操作:

$.each(items, function (i, item) {
    $('#mySelect').append($('<option>', { 
        value: item.value,
        text : item.text 
    }));
});

#2


139  

I agree Ashish, this did NOT work in IE8 (yet did in FF):

我同意Ashish,这在IE8中并没有起作用(但在FF中):

$("#selectList").append(new Option("option text", "value"));

This DID work:

这做的工作:

var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);

#3


69  

You can add option using following syntax, Also you can visit to way handle option in jQuery for more details.

您可以使用以下语法添加选项,也可以访问jQuery中的way handle选项以获得更多细节。

  1. $('#select').append($('<option>', {value:1, text:'One'}));

    $(" #选择”)。追加($(' <选项> ',{价值:1、文本:‘一个’}));

  2. $('#select').append('<option value="1">One</option>');

    $(" #选择”)。追加(“ <选项值= " 1> < /选项>“);

  3. var option = new Option(text, value); $('#select').append($(option));

    var选项=新选项(文本、值);$(" #选择“).append($(选项);

#4


40  

If the option name or value is dynamic, you won't want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:

如果选项名或值是动态的,您就不需要担心在其中转义特殊字符;在这一点上,您可能更喜欢简单的DOM方法:

var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');

#5


32  

Option 1-

You can try this-

你可以试试这个

$('#selectID').append($('<option>',
 {
    value: value_variable,
    text : text_variable
}));

Like this-

像这样,

for (i = 0; i < 10; i++)
{ 
     $('#mySelect').append($('<option>',
     {
        value: i,
        text : "Option "+i 
    }));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id='mySelect'></select>

Option 2-

Or try this-

或者试试这个

$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );

Like this-

像这样,

for (i = 0; i < 10; i++)
{ 
     $('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id='mySelect'></select>

#6


16  

That works well.

这工作得很好。

If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.

如果添加多个选项元素,我建议您一次执行append,而不是在每个元素上执行追加操作。

#7


16  

for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+

无论出于什么原因做$(“#myselect”)。追加(新选项(“文本”、“文本”));在IE7+中不适合我。

I had to use $("#myselect").html("<option value='text'>text</option>");

我必须使用$(“#myselect”)。html(“ <选项值= '文本'> 文本< /选项> ");

#8


13  

To help performance you should try to only alter the DOM once, even more so if you are adding many options.

为了帮助性能,您应该尝试只修改DOM一次,如果您添加了许多选项,那么就更应该这样做。

var html = '';

for (var i = 0, len = data.length; i < len; ++i) {
    html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}           

$('#select').append(html);

#9


12  

I like to use non jquery approach:

我喜欢使用非jquery方法:

mySelect.add(new Option('My option', 1));

#10


10  

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

#11


9  

You can add options dynamically into dropdown as shown in below example. Here in this example I have taken array data and binded those array value to dropdown as shown in output screenshot

您可以动态地添加选项,如下面的示例所示。在本例中,我使用了数组数据,并将这些数组值绑定到下拉,如输出屏幕截图所示。

Output:

输出:

使用jQuery为添加选项?

var resultData=["Mumbai","Delhi","Chennai","Goa"]
$(document).ready(function(){
   var myselect = $('<select>');
     $.each(resultData, function(index, key) {
	     myselect.append( $('<option></option>').val(key).html(key) );
       });
      $('#selectCity').append(myselect.html());
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>

<select  id="selectCity">

</select>

#12


8  

var select = $('#myselect');
var newOptions = {
                'red' : 'Red',
                'blue' : 'Blue',
                'green' : 'Green',
                'yellow' : 'Yellow'
            };
$('option', select).remove();
$.each(newOptions, function(text, key) {
    var option = new Option(key, text);
    select.append($(option));
});

#13


7  

Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:

在任何答案中都没有提到,但有用的是你想要那个选项也被选中,你可以添加:

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

#14


7  

This very simple things. You can do this by this way

这个非常简单的事情。你可以这样做。

$('#select_id').append('<option value="five" selected="selected">Five</option>');

or

$('#select_id').append($('<option>', {
                    value: 1,
                    text: 'One'
                }));

Here is the full guide

这是完整的指南。

#15


4  

There are two ways. You can use either of these two.

有两种方法。你可以用这两个中的任意一个。

First:

第一:

$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');

Second:

第二:

$.each(dataCollecton, function(val, text) {            
    options.append($('<option></option>').val(text.route).html(text.route));
});

#16


3  

You can append and set the Value attribute with text:

您可以使用文本添加和设置值属性:

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

#17


3  

We found some problem when you append option and use jquery validate. You must click one item in select multiple list. You will add this code to handle:

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

$("#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

使用jQuery为添加选项?

#18


2  

If you want to insert the new option at a specific index in the select:

如果您想在select的特定索引中插入新选项:

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

This will insert the "New Item" as the 3rd item in the select.

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

#19


2  

This is just a quick points for best performance

这仅仅是最佳性能的一个快速点。

always when you are dealing with many options, build a big string and then add it to the 'select' for best performance

在处理许多选项时,要构建一个大字符串,然后将其添加到“select”中以获得最佳性能。

f.g.

f.g。

var $mySelect = $('#mySelect'); var str = '';

var mySelect =美元(“# mySelect”);var str = ";

$.each(items, function (i, item) {
    // IMPORTANT: no selectors inside the loop (for the best performance)
    str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string

$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');

Even faster

var str = ""; 
for(var i; i = 0; i < arr.length; i++){
    str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}    
$mySelect.html(str);
$mySelect.multiSelect('refresh');

#20


1  

if u have optgroup inside select, u got error in DOM.

如果在select中有optgroup,则在DOM中出错。

I think a best way:

我认为最好的方法是:

$("#select option:last").after($('<option value="1">my option</option>'));

#21


1  

U can try below code to append to option

你可以试试下面的代码来添加选项。

  <select id="mySelect"></select>

    <script>
          $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
    </script>

#22


1  

$('#select_id').append($('<option>',{ value: v, text: t }));

#23


1  

This is the way i did it, with a button to add each select tag.

这是我的方法,用一个按钮来添加每个选择标签。

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

#24


1  

How about this

这个怎么样

var numbers = [1, 2, 3, 4, 5];
var option = '';

for (var i=0;i<numbers.length;i++){
     option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
    }

    $('#items').append(option);

相关文章