jQuery Set Select Index

2019-01-05 07:23发布

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!

23条回答
混吃等死
2楼-- · 2019-01-05 07:50
//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);
        }
    });
查看更多
乱世女痞
3楼-- · 2019-01-05 07:51

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.

查看更多
唯我独甜
4楼-- · 2019-01-05 07:51

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');
查看更多
仙女界的扛把子
5楼-- · 2019-01-05 07:52

Hope this could help Too

$('#selectBox option[value="3"]').attr('selected', true);
查看更多
smile是对你的礼貌
6楼-- · 2019-01-05 07:52

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.

查看更多
干净又极端
7楼-- · 2019-01-05 07:55

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

查看更多
登录 后发表回答