Search code examples
jquerytwitter-bootstrapbootstrap-multiselect

Bootstrap Multiselect not posting 'selectAllValue' in form


I am having trouble including the value set for 'selectAllValue' when submitting a form. Rather than include the value in the post, it is being removed and only the options that are selected are being passed. How can I update the multiselect so that when the form posts, it includes all the values selected (ie 1,2,3,4,5) and also the selectAllValue of 0? The form is:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="http://www.peoplevalue.co.uk/dev/css/bootstrap-multiselect.css" type="text/css">
</head>
<body>
<div id="filteroptions"></div>
<form action="Index" class="form-horizontal" id="filterForm" method="post" >
  <select class="form-control multiselect" id="Roles" multiple="multiple" name="Roles">
    <option selected="selected" value="5">Role 5</option>
    <option selected="selected" value="4">Role 4</option>
    <option selected="selected" value="3">Role 3</option>
    <option selected="selected" value="2">Role 2</option>
    <option selected="selected" value="1">Role 1</option>
  </select>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js" type="text/javascript"></script> 
<script src="http://www.peoplevalue.co.uk/dev/js/bootstrap-multiselect.js" type="text/javascript"></script> 
<script type="text/javascript">
      $('.multiselect').multiselect({
         includeSelectAllOption: true,
         selectAllValue: 0,
         onChange: function(option, checked, select) {
            var Roles = $("#Roles").val();
             document.getElementById("filteroptions").innerHTML = ("Form Contents: " + Roles) ;
      }  
       });
   </script>
</body>
</html>

Solution

  • You can Initialize an array and push one by one values "Select All Value" and Selected options values

        var selected = [];
        selected.push($("input[type=checkbox]:checked").val()); // Get Selected option value
    
        var brands = $('#Roles option:selected');
    
         $(brands).each(function (index, brand) {
            selected.push([$(this).val()]);
            });
    

    includes all the values selected and also the "selectAllValue