Set the selected index of a Dropdown using jQuery

后端 未结 10 791
离开以前
离开以前 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: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);
    

提交回复
热议问题