jQuery集选择索引

发布于 2025-01-23 14:48:40 字数 672 浏览 3 评论 0原文

我有一个选择框:

<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根据其索引设置选项?

谢谢!

I have an select box:

<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>

I'd like to set one of the options as "selected" based on it's selected index.

For example, if I am trying to set "Number 3", I'm trying this:

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

But this doesn't work. How can I set an option as selected based on it's index using jQuery?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

墨小沫ゞ 2025-01-30 14:48:40

注释:答案取决于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)在此示例中也可以使用,但是非数字值必须是字符串,因此我选择了一个字符串以保持一致性。
(例如&lt; option value =“ hello”&gt; number3&lt;/option&gt;要求您使用.val(“ hello”)

NOTE: answer is dependent upon 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

Thanks for the comment, .get won't work since it returns a DOM element, not a jQuery one. Keep in mind the .eq function can be used outside of the selector as well if you prefer.

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

You can also be more terse/readable if you want to use the value, instead of relying on selecting a specific index:

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

Note: .val(3) works as well for this example, but non-numeric values must be strings, so I chose a string for consistency.
(e.g. <option value="hello">Number3</option> requires you to use .val("hello"))

波浪屿的海角声 2025-01-30 14:48:40

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

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

您的选择列表:

<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号”。

This may also be useful, so I thought I'd add it here.

If you would like to select a value based on the item's value and not the index of that item then you can do the following:

Your select list:

<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>

The jquery:

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

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

The selected item would be "Number 2" now.

勿忘初心 2025-01-30 14:48:40

而是尝试一下:

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

Try this instead:

$("#selectBox").val(3);
谈情不如逗狗 2025-01-30 14:48:40

更简单:

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

Even simpler:

$('#selectBox option')[3].selected = true;
为你鎻心 2025-01-30 14:48:40
# 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();
# Set element with index
$("#select option:eq(2)").attr("selected", "selected");

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

when you want to select with top ways for set selection , you can use
$('#select option').removeAttr('selected'); for remove previous selects .

# 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();
挽你眉间 2025-01-30 14:48:40

重要的是要理解的是val() 选择元素返回所选选项的值,而不是selected> selected IndiNdex 在JavaScript中。

要选择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

*但是要选择多个选项,代码>&lt; select&gt; 元素必须具有多个属性,否则它将无法使用。

What's important to understand is that val() for a select element returns the value of the selected option, but not the number of element as does selectedIndex in javascript.

To select the option with value="7" you can simply use:

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

To deselect the option use an empty array:

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

And of course you can select multiple options*:

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

*However to select multiple options, your <select> element must have a MULTIPLE attribute, otherwise it won't work.

糖粟与秋泊 2025-01-30 14:48:40

我一直在道具(“选定”)的问题上,以下内容一直对我有用:

//first remove the current value
$("#selectBox").children().removeAttr("selected");
$("#selectBox").children().eq(index).attr('selected', 'selected');

I've always had issues with prop('selected'), the following has always worked for me:

//first remove the current value
$("#selectBox").children().removeAttr("selected");
$("#selectBox").children().eq(index).attr('selected', 'selected');
信愁 2025-01-30 14:48:40

尝试以下操作:

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

最终,触发一个。变换事件:

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

Try this:

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

Eventually, trigger a .change event :

$('select#mySelect').prop('selectedIndex', optionIndex).change();
国产ˉ祖宗 2025-01-30 14:48:40

希望这也会有所帮助

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

Hope this could help Too

$('#selectBox option[value="3"]').attr('selected', true);
白云不回头 2025-01-30 14:48:40

纯javascript selectionindexex attribute是正确的方法-browser:

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

来设置另一个。

<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>

这是一个JSFIDDLEDLEDLEDLEDLEDLEDLEDDLEDLEDLEDDLEDLEDLEDDLEDLEDLEDDLEDLEDLEDDLEDLED DEMO ,使用两个下拉deptowns使用一个 如果您想要的是选项标签上的“选择”属性(这是小提琴):

$('#selectBox option').removeAttr('selected')
   .eq(this.selectedIndex).attr('selected','selected');

The pure javascript selectedIndex attribute is the right way to go because,it's pure javascript and works cross-browser:

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

Here is a jsfiddle demo with two dropdowns using one to set the other:

<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>

You can also call this before changing the selectedIndex if what you want is the "selected" attribute on the option tag (here is the fiddle):

$('#selectBox option').removeAttr('selected')
   .eq(this.selectedIndex).attr('selected','selected');
谁的新欢旧爱 2025-01-30 14:48:40

选择第3个选项

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

jsfiddle上的示例

select 3rd option

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

Example on jsfiddle

渡你暖光 2025-01-30 14:48:40

nb:

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

是不正确的,数组deprence可以使您获得dom对象,而不是jQuery对象,因此它将使用typeError失败,例如在ff中使用:“ $('#selectbox option')[3] .attr()。功能。”

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."

紅太極 2025-01-30 14:48:40

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

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

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

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

eq()获取使用指定索引的jQuery设置为元素的jQuery。它比$($('#SelectBox option')。get(3))更清楚。并不是那么高效。 $($('#SelectBox选项')[3])更有效(请参阅测试案例)。

您实际上并不需要jQuery对象。这将解决问题:

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

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

=“ http://api.jquery.com/eq/” rel =“ nofollow noreferrer”> http://api.jquery.com/eq/

另一个非常重要的一点:

属性“选择” is不是您如何指定选定的广播按钮(至少在Firefox和Chrome中)。使用“检查”属性:

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

Check-Boxes也是如此。

To clarify Marc's and John Kugelman's answers, you could use:

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

get() will not work if used in the way specified because it gets the DOM object, not a jQuery object, so the following solution will not work:

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

eq() gets filters the jQuery set to that of the element with the specified index. It's clearer than $($('#selectBox option').get(3)). It's not all that efficient. $($('#selectBox option')[3]) is more efficient (see test case).

You don't actually need the jQuery object though. This will do the trick:

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

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

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

One other vitally important point:

The attribute "selected" is not how you specify a selected radio button (in Firefox and Chrome at least). Use the "checked" attribute:

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

The same goes for check-boxes.

潦草背影 2025-01-30 14:48:40

在1.4.4中,您会收到一个错误: $(“#selectbox option”)[3] .ATTR不是函数

此工作:$('#名称选项:eq(idx) ').attr('selected',true);

其中#name是选择ID和IDX是您要选择的选项值。

In 1.4.4 you get an error: $("#selectBox option")[3].attr is not a function

This works: $('#name option:eq(idx)').attr('selected', true);

Where #name is select id and idx is the option value you want selected.

请远离我 2025-01-30 14:48:40

进行示例:

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

我经常使用触发器('Change')将其与ID select select = selecta1和position_index = 0(select中的frist option)一起

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

I often use trigger ('change') to make it work

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

Example with id select = selectA1 and position_index = 0 (frist option in select):

$('#selectA1 option:eq(0)').prop('selected', true).trigger('change');
梦中楼上月下 2025-01-30 14:48:40
//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);
        }
    });
//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);
        }
    });
百合的盛世恋 2025-01-30 14:48:40
$('#selectBox option').get(3).attr('selected', 'selected')

当使用上述内容时,我一直在Webkit(Chrome)中遇到错误,说:

“ uncovering typeError:对象#没有方法'attr'”

此语法阻止了这些错误。

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

When using the above I kept getting errors in webkit (Chrome) saying:

"Uncaught TypeError: Object # has no method 'attr'"

This syntax stops those errors.

$($('#selectBox  option').get(3)).attr('selected', 'selected');
尸血腥色 2025-01-30 14:48:40

根据选择列表中的值(尤其是在选项值具有空间或怪异字符)中的值:

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

另外,如果您有下拉列表(而不是多选择),则可能想要要进行break;,这样就不会覆盖第一值发现。

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.

楠木可依 2025-01-30 14:48:40

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

$("#selectBox").get(0).selectedIndex = 1; 

I need a solution that has no hard coded values in the js file; using selectedIndex. Most of the given solutions failed one browser. This appears to work in FF10 and IE8 (can someone else test in other versions)

$("#selectBox").get(0).selectedIndex = 1; 
别想她 2025-01-30 14:48:40

如果您只想选择项目的特定属性的项目,则类型[Prop = Val]的JQuery选项将获得该项目。现在,我不在乎索引,我只是想要该项目的价值。

$('#mySelect options[value=3]).attr('selected', 'selected');

If you just want to select an item based of a particular property of an item then jQuery option of type[prop=val] will get that item. Now I don't care about the index I just wanted the item by its value.

$('#mySelect options[value=3]).attr('selected', 'selected');
亢潮 2025-01-30 14:48:40

我遇到了同样的问题。
首先,您需要进行事件(即首先发生哪个事件)。

例如:

第一个事件正在生成带有选项的选择框。

事件是使用任何功能(例如val()等选择默认选项。

第二 >。

为了实现这一目标,请说 gentratesElectbox()(用于恢复选择框)和 selectDefaultOption()

您需要确保 selectdeff> selectDefaultOption())仅在执行 generateElectbox()之后才能调用

I faced same problem.
First you need go through the events (i.e which event is happening first).

For example:

The First event is generating select box with options.

The Second event is selecting default option using any function such as val() etc.

You should ensure that the Second event should happen after the First event.

To achieve this take two functions lets say generateSelectbox() (for genrating select box) and selectDefaultOption()

You need to ensure that selectDefaultOption() should be called only after the execution of generateSelectbox()

暮凉 2025-01-30 14:48:40

如果您的SelectBox是一个多重,您也可以启动多个值:

$('#selectBox').val(['A', 'B', 'C']);

You can also init multiple values if your selectbox is a multipl:

$('#selectBox').val(['A', 'B', 'C']);
茶底世界 2025-01-30 14:48:40

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

$("#selectbox")[0].selectedIndex = 1;

After spending too much time, this one worked for me.

$("#selectbox")[0].selectedIndex = 1;
邮友 2025-01-30 14:48:40

您可以动态设置SelectOption变量值,并选择选项。您可以尝试以下代码

 <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代码:

   <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   <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>

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   <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>

蝶舞 2025-01-30 14:48:40

不久:

$(“#selectbox”)。attr(“ selectionIndex”,index)

其中索引是所选索引作为整数。

Shortly:

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

where index is the selected index as integer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文