jQuery to retrieve and set selected option value of html select element

前端 未结 9 1314
醉梦人生
醉梦人生 2020-11-28 21:15

I am attempting to retrieve and set the selected value of a select element (drop down list) with jQuery.

for retrievel i have tried $(\"#myId\").find(\':select

相关标签:
9条回答
  • 2020-11-28 22:10

    $('#myId').val() should do it, failing that I would try:

    $('#myId option:selected').val()
    
    0 讨论(0)
  • 2020-11-28 22:14

    I know this is old but I just had a bear of a time with Razor, could not get it to work no matter how hard I tried. Kept coming back as "undefined" no matter if I used "text" or "html" for attribute. Finally I added "data-value" attribute to the option and it read that just fine.

     <option value="1" data-value="MyText">MyText</option>
    
     var DisplayText = $(this).find("option:selected").attr("data-value");
    
    0 讨论(0)
  • 2020-11-28 22:18

    When setting with JQM, don't forget to update the UI:

    $('#selectId').val('newValue').selectmenu('refresh', true);
    
    0 讨论(0)
提交回复
热议问题