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

前端 未结 9 1313
醉梦人生
醉梦人生 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 21:52

    to get/set the actual selectedIndex property of the select element use:

    $("#select-id").prop("selectedIndex");
    
    $("#select-id").prop("selectedIndex",1);
    
    0 讨论(0)
  • 2020-11-28 21:57

    $("#myId").val() should work if myid is the select element id!

    This would set the selected item: $("#myId").val('VALUE');

    0 讨论(0)
  • 2020-11-28 21:57

    $( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding

    <select id="myId">
        <option value="1">Mr</option>
        <option value="2">Mrs</option>
        <option value="3">Ms</option>`
        <option value="4">Dr</option>
        <option value="5">Prof</option>
    </select>
    
    0 讨论(0)
  • 2020-11-28 22:00

    Suppose you have created a Drop Down list using SELECT tag like as follows,

    <select id="Country">
    

    Now if you want to see what is the selected value from drop down using JQuery then, simply put following line to retrieve that value..

    var result= $("#Country option:selected").text();
    

    it will work fine.

    0 讨论(0)
  • 2020-11-28 22:01

    Try this

    $('#your_select_element_id').val('your_value').attr().add('selected');
    
    0 讨论(0)
  • 2020-11-28 22:03

    The way you have it is correct at the moment. Either the id of the select is not what you say or you have some issues in the dom.

    Check the Id of the element and also check your markup validates at here at W3c.

    Without a valid dom jQuery cannot work correctly with the selectors.

    If the id's are correct and your dom validates then the following applies:

    To Read Select Option Value

    $('#selectId').val();
    

    To Set Select Option Value

    $('#selectId').val('newValue');
    

    To Read Selected Text

    $('#selectId>option:selected').text();
    
    0 讨论(0)
提交回复
热议问题