266

我有一个选择框:

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
  <option value="3">Number 3</option>
  <option value="4">Number 4</option>
  <option value="5">Number 5</option>
  <option value="6">Number 6</option>
  <option value="7">Number 7</option>
</select>

我想根据它的选定索引将其中一个选项设置为“选定”。

例如,如果我试图设置“数字 3”,我正在尝试这个:

$('#selectBox')[3].attr('selected', 'selected');

但这不起作用。如何使用 jQuery 根据它的索引设置一个选项?

谢谢!

4

25 回答 25

462

注意:答案取决于 jQuery 1.6.1+

$('#selectBox :nth-child(4)').prop('selected', true); // To select via index
$('#selectBox option:eq(3)').prop('selected', true);  // To select via value

感谢您的评论,.get因为它返回一个 DOM 元素,而不是 jQuery 元素,所以它不起作用。请记住,.eq如果您愿意,也可以在选择器之外使用该功能。

$('#selectBox option').eq(3).prop('selected', true);

如果你想使用value,你也可以更简洁/可读,而不是依赖于选择特定的index

$("#selectBox").val("3");

注意: .val(3)这个例子也适用,但非数字值必须是字符串,所以我选择了一个字符串以保持一致性。
(例如<option value="hello">Number3</option>要求您使用.val("hello")

于 2009-08-14T22:32:57.563 回答
118

这也可能有用,所以我想我会在这里添加它。

如果您想根据项目的值而不是该项目的索引来选择一个值,那么您可以执行以下操作:

您的选择列表:

<select id="selectBox">
    <option value="A">Number 0</option>
    <option value="B">Number 1</option>
    <option value="C">Number 2</option>
    <option value="D">Number 3</option>
    <option value="E">Number 4</option>
    <option value="F">Number 5</option>
    <option value="G">Number 6</option>
    <option value="H">Number 7</option>
</select>

jQuery:

$('#selectBox option[value=C]').attr('selected', 'selected');

$('#selectBox option[value=C]').prop('selected', true);

所选项目现在将是“数字 2”。

于 2010-08-11T14:34:23.973 回答
68

试试这个:

$("#selectBox").val(3);
于 2009-08-14T22:31:11.217 回答
51

更简单:

$('#selectBox option')[3].selected = true;
于 2011-02-22T07:50:10.270 回答
17
# Set element with index
$("#select option:eq(2)").attr("selected", "selected");

# Set element by text
$("#select").val("option Text").attr("selected", "selected");

当您想使用顶级方式进行选择时,您可以使用
$('#select option').removeAttr('selected');删除以前的选择。

# Set element by value
$("#select").val("2");

# Get selected text
$("#select").children("option:selected").text();  # use attr() for get attributes
$("#select option:selected").text(); # use attr() for get attributes 

# Get selected value
$("#select option:selected").val();
$("#select").children("option:selected").val();
$("#select option:selected").prevAll().size();
$("option:selected",this).val();

# Get selected index
$("#select option:selected").index();
$("#select option").index($("#select option:selected"));

# Select First Option
$("#select option:first");

# Select Last Item
$("#select option:last").remove();


# Replace item with new one
$("#select option:eq(1)").replaceWith("<option value='2'>new option</option>");

# Remove an item
$("#select option:eq(0)").remove();
于 2013-04-09T12:58:23.490 回答
11

重要的是要了解val()元素select返回所选选项的值,而不是selectedIndexjavascript 中的元素数量。

要选择选项,value="7"您可以简单地使用:

$('#selectBox').val(7); //this will select the option with value 7.

要取消选择该选项,请使用空数组:

$('#selectBox').val([]); //this is the best way to deselect the options

当然,您可以选择多个选项*:

$('#selectBox').val([1,4,7]); //will select options with values 1,4 and 7

*但是要选择多个选项,您的<select>元素必须有一个MULTIPLE属性,否则它将不起作用。

于 2012-08-31T15:50:09.510 回答
11

我一直遇到 prop('selected') 的问题,以下一直对我有用:

//first remove the current value
$("#selectBox").children().removeAttr("selected");
$("#selectBox").children().eq(index).attr('selected', 'selected');
于 2016-05-26T15:59:46.760 回答
8

尝试这个:

$('select#mySelect').prop('selectedIndex', optionIndex);

最终,触发一个 .change 事件:

$('select#mySelect').prop('selectedIndex', optionIndex).change();
于 2014-09-05T15:32:19.350 回答
6

希望这也能有所帮助

$('#selectBox option[value="3"]').attr('selected', true);
于 2013-05-06T11:47:27.763 回答
5

选择第三个选项

$('#selectBox').val($('#selectBox option').eq(2).val());

jsfiddle 上的示例

于 2013-09-03T13:21:04.560 回答
4

NB:

$('#selectBox option')[3].attr('selected', 'selected') 

is incorrect, the array deference gets you the dom object, not a jquery object, so it will fail with a TypeError, for instance in FF with: "$('#selectBox option')[3].attr() not a function."

于 2010-12-08T17:40:07.180 回答
4

为了澄清 Marc 和 John Kugelman 的答案,您可以使用:

$('#selectBox option').eq(3).attr('selected', 'selected')

get()如果以指定的方式使用将不起作用,因为它获取的是 DOM 对象,而不是 jQuery 对象,因此以下解决方案将不起作用:

$('#selectBox option').get(3).attr('selected', 'selected')

eq()将 jQuery 设置为具有指定索引的元素的过滤器。它比 更清楚$($('#selectBox option').get(3))。这并不是那么有效。$($('#selectBox option')[3])效率更高(参见测试用例)。

不过,您实际上并不需要 jQuery 对象。这可以解决问题:

$('#selectBox option')[3].selected = true;

http://api.jquery.com/get/

http://api.jquery.com/eq/

另一个至关重要的点:

“selected”属性不是您指定选定单选按钮的方式(至少在 Firefox 和 Chrome 中)。使用“checked”属性:

$('#selectBox option')[3].checked = true;

复选框也是如此。

于 2011-06-08T14:44:21.667 回答
4

纯 javascript selectedIndex属性是正确的方法,因为它是纯 javascript 并且可以跨浏览器工作:

$('#selectBox')[0].selectedIndex=4;

这是一个 jsfiddle 演示,其中有两个下拉菜单,使用一个来设置另一个:

<select onchange="$('#selectBox')[0].selectedIndex=this.selectedIndex">
  <option>0</option>
  <option>1</option>
  <option>2</option>
</select>

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
</select>

如果您想要的是选项标签上的“选定”属性(这里是小提琴),您也可以在更改 selectedIndex 之前调用它:

$('#selectBox option').removeAttr('selected')
   .eq(this.selectedIndex).attr('selected','selected');
于 2013-06-27T02:01:43.997 回答
4

在 1.4.4 中出现错误: $("#selectBox option")[3].attr is not a function

这有效:$('#name option:eq(idx)').attr('selected', true);

#nameselect id在哪里,idx是您要选择的选项值。

于 2010-12-20T12:45:56.237 回答
4

我经常使用触发器('change')来使其工作

$('#selectBox option:eq(position_index)').prop('selected', true).trigger('change');

id select = selectA1 和 position_index = 0 的示例(选择中的第一个选项):

$('#selectA1 option:eq(0)').prop('selected', true).trigger('change');
于 2019-01-10T03:39:20.713 回答
2
//funcion para seleccionar por el text del select
var text = '';
var canal = ($("#name_canal").val()).split(' ');
$('#id_empresa option').each(function(i, option) {
        text = $('#id_empresa option:eq('+i+')').text();
        if(text.toLowerCase() == canal[0].toLowerCase()){
            $('#id_empresa option:eq('+i+')').attr('selected', true);
        }
    });
于 2011-10-21T03:49:35.673 回答
1

如果您的选择框是一个乘数,您也可以初始化多个值:

$('#selectBox').val(['A', 'B', 'C']);
于 2013-01-08T14:24:44.367 回答
1

如果您只想根据项目的特定属性选择项目,则类型 [prop=val] 的 jQuery 选项将获取该项目。现在我不关心我只想要项目的值的索引。

$('#mySelect options[value=3]).attr('selected', 'selected');
于 2011-12-14T22:53:30.243 回答
1

我需要一个在 js 文件中没有硬编码值的解决方案;使用selectedIndex. 大多数给定的解决方案都使一个浏览器失败。这似乎适用于 FF10 和 IE8(其他人可以在其他版本中测试)

$("#selectBox").get(0).selectedIndex = 1; 
于 2012-04-02T16:33:05.050 回答
1
$('#selectBox option').get(3).attr('selected', 'selected')

使用上述内容时,我在 webkit (Chrome) 中不断收到错误消息:

“未捕获的类型错误:对象 # 没有方法 'attr'”

此语法会阻止这些错误。

$($('#selectBox  option').get(3)).attr('selected', 'selected');
于 2011-03-09T11:02:08.277 回答
1

我遇到了同样的问题。首先,您需要查看事件(即首先发生的事件)。

例如:

一个事件 是生成带有选项的选择框。

第二个事件是使用任何函数(例如 val() 等)选择默认选项。

您应该确保第二个事件应该在第一个事件之后发生。

要实现这一点,需要两个函数,比如说generateSelectbox()(用于生成选择框)和selectDefaultOption()

您需要确保仅在执行generateSelectbox()之后才应调用selectDefaultOption( )

于 2012-12-04T05:21:06.583 回答
1

Select the item based on the value in the select list (especially if the option values have a space or weird character in it) by simply doing this:

$("#SelectList option").each(function () {
    if ($(this).val() == "1:00 PM")
        $(this).attr('selected', 'selected');
});

Also, if you have a dropdown (as opposed to a multi-select) you may want to do a break; so you don't get the first-value-found to be overwritten.

于 2012-05-22T00:14:50.810 回答
0

you can set selectoption variable value dynamically as well as option will be selected.You can try following code

code:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

      $(function(){
            $('#allcheck').click(function(){
             // $('#select_option').val([1,2,5]);also can use multi selectbox
              // $('#select_option').val(1);
               var selectoption=3;
           $("#selectBox>option[value="+selectoption+"]").attr('selected', 'selected');
    });

});

HTML CODE:

   <select id="selectBox">
       <option value="0">Number 0</option>
       <option value="1">Number 1</option>
       <option value="2">Number 2</option>
       <option value="3">Number 3</option>
       <option value="4">Number 4</option>
       <option value="5">Number 5</option>
       <option value="6">Number 6</option>
       <option value="7">Number 7</option>
 </select> <br>
<strong>Select&nbsp;&nbsp; <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>

于 2013-02-27T11:44:01.760 回答
0

在花了太多时间之后,这个对我有用。

$("#selectbox")[0].selectedIndex = 1;
于 2021-04-13T03:07:12.267 回答
-2

不久:

$("#selectBox").attr("selectedIndex",index)

其中 index 是选定的整数索引。

于 2012-03-31T21:09:35.240 回答