jQuery Set Select Index

后端 未结 24 1608
无人共我
无人共我 2020-11-27 09:52

I have an select box:


                        
    
提交评论

  • 2020-11-27 10:18

    Try this:

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

    Eventually, trigger a .change event :

    $('select#mySelect').prop('selectedIndex', optionIndex).change();
    
    0 讨论(0)
  • 2020-11-27 10:18

    select 3rd option

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

    Example on jsfiddle

    0 讨论(0)
  • 2020-11-27 10:19
    //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);
            }
        });
    
    0 讨论(0)
  • 2020-11-27 10:19

    Shortly:

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

    where index is the selected index as integer.

    0 讨论(0)
  • 2020-11-27 10:20

    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.

    0 讨论(0)
  • 提交回复
    热议问题