Preselecting option in multiselect using val()

后端 未结 2 1302
野性不改
野性不改 2021-01-21 21:20

How do you preselect an option in a multiple select html tag using jquery\'s val()?

What I mean by this is that say you have a multiselect component and you want some o

相关标签:
2条回答
  • 2021-01-21 21:53

    Assuming I've understood your question correctly, you can pass an array of values to the .val() method:

    $("#yourSelect").val(["value1", "value2"]);
    

    Here's a working example.

    0 讨论(0)
  • 2021-01-21 21:58

    You can do it like this:

    HTML:

    <select multiple="multiple">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>​
    

    jQuery:

    $("select").val(["volvo", "mercedes"]).prop("selected", true);
    

    Here's a fiddle with the example: http://jsfiddle.net/HCm3e/

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