如何设置从jquery中实现多选所选值的实现

时间:2018-02-01 12:08:43

标签: materialize

我想在我的页面初始加载时将值设置为选中,但我无法设置它们。

这是我的HTML标记:

<select multiple id="access_rights">
 <option value="default" disabled selected>Choose your options</option>
 <option value="create">Create</option> 
 <option value="read">Read</option> 
 <option value="update">Update</option> 
 <option value="delete">Delete</option> 
</select> <label>Select Access Rights</label>`

现在我想在首次加载页面时选择“创建”和“更新”作为默认值。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

参见工作演示:

&#13;
&#13;
$(document).ready(function() {
    $('select').material_select();
});


var selectedOptions=[
  "create",
  "update"
];

$.each(selectedOptions, function(i,e){
    $("#access_rights option[value='" + e + "']").prop("selected", true);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">

 <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
 

<label for="access_rights">Select Access Rights</label>
<select id="access_rights" multiple>  
  <option value="default" disabled>Choose your options</option>        <option value="create">Create</option>                     <option value="read">Read</option>                         <option value="update">Update</option>                     <option value="delete">Delete</option>                 </select> 
  
&#13;
&#13;
&#13;

答案 1 :(得分:0)

只需在创建和更新选项中使用selected即可。例如: -

<select multiple id="access_rights"> <option value="default" disabled>Choose your options</option> <option value="create" selected>Create</option> <option value="read">Read</option> <option value="update" selected>Update</option> <option value="delete">Delete</option> </select>选择访问权限

答案 2 :(得分:0)

    $( document ).ready(function() {
    $(".select-wrapper").each(function() {
      var wrapper = this;
      $(this).find("ul>li").each(function() {
          var li = this;
          var option_text = $(this).text();

          $(wrapper).find("select option:selected").each(function() {
             var selected_text = $(this).text();

             if(option_text == selected_text) {
                //$(li).addClass("active selected");
                //$(li).find("input").prop('checked', true);
                $(li).click();
             }
          });
      });
    });
    });