Set the selected index of a Dropdown using jQuery

后端 未结 10 792
离开以前
离开以前 2020-11-30 17:49

How do I set the index of a dropdown in jQuery if the way I\'m finding the control is as follows:

$(\"*[id$=\'\" + originalId + \"\']\") 

I

相关标签:
10条回答
  • 2020-11-30 18:18

    JQuery code:

    $("#sel_status").prop('selectedIndex',1);
    

    Jsp Code:

    Status:
    <select name="sel_status"
        id="sel_status">
        <option value="1">-Status-</option>
        <option>ALL</option>
        <option>SENT</option>
        <option>RECEIVED</option>
        <option>DEACTIVE</option>
    </select>
    
    0 讨论(0)
  • 2020-11-30 18:20

    I'm using

    $('#elem').val('xyz');
    

    to select the option element that has value='xyz'

    0 讨论(0)
  • 2020-11-30 18:21

    Just found this, it works for me and I personally find it easier to read.

    This will set the actual index just like gnarf's answer number 3 option.

    // sets selected index of a select box the actual index of 0 
    $("select#elem").attr('selectedIndex', 0);
    

    This didn't used to work but does now... see bug: http://dev.jquery.com/ticket/1474

    Addendum

    As recommended in the comments use :

    $("select#elem").prop('selectedIndex', 0);

    0 讨论(0)
  • 2020-11-30 18:24

    First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element.

    $(".myselect")
    

    To answer your question though, there are a few ways to change the select elements value in jQuery

    // sets selected index of a select box to the option with the value "0"
    $("select#elem").val('0'); 
    
    // sets selected index of a select box to the option with the value ""
    $("select#elem").val(''); 
    
    // sets selected index to first item using the DOM
    $("select#elem")[0].selectedIndex = 0;
    
    // sets selected index to first item using jQuery (can work on multiple elements)
    $("select#elem").prop('selectedIndex', 0);
    
    0 讨论(0)
  • 2020-11-30 18:33

    To select the 2nd option

    $('#your-select-box-id :nth-child(2)').prop('selected', true);
    

    Here we add the `trigger('change') to make the event fire.

    $('#your-select-box-id :nth-child(2)').prop('selected', true).trigger('change');
    
    0 讨论(0)
  • 2020-11-30 18:39

    This also work proper in chrome and internet Explorer

    $("#MainContent_cmbEvalStatus").prop("selectedIndex", 1).change();
    

    Put according your choice possition value of DropDown 0,1,2,3,4.....

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