Select multiple checkboxes by javascript

28/10/2015 10:47

<!DOCTYPE html>
<html>
<body>

<h2>Checkbox list</h2>

<input type="hidden" value="1">
<h3>Multi Operation for list items</h3>
<input type="button" value ="Select all" onclick="checkAll()"/>
<input type="button" value="Deselect all" onclick="uncheckAll()"/>
<input type="button" value="Save selected" onclick="operationForSelected()"/>
<table>
    <tbody><tr>
        <th>
            Description
        </th>
        <th></th>
        <th>
           Order
        </th>
    </tr>

    <tr>
        <td><input type="checkbox" id="1" value="1" onchange="AddChoice(this.id)" name="priority"></td>
        <td>
            <a href="#">Item 1</a>
        </td>
     </tr>
  <tr>
        <td><input type="checkbox" id="2" value="2" onchange="AddChoice(this.id)" name="priority"></td>
        <td>
            <a href="#">Item 2</a>
        </td> 
     </tr>
  <tr>
        <td><input type="checkbox" id="3" value="4" onchange="AddChoice(this.id)" name="priority"></td>
        <td>
            <a href="#">Item 3</a>
        </td> 
    </tr>
   </tbody></table>
   Selected choices: <span id="selectedChoicesText"></span>
<script>

var selectedChoices = [];

function AddChoice(chboxId) {
 if(document.getElementById(chboxId).checked) {
  selectedChoices = selectedChoices.filter(function(e){return e!==chboxId})//remove existing item first
  selectedChoices.push(chboxId);
 }
 else {
  selectedChoices = selectedChoices.filter(function(e){return e!==chboxId})
 }
    document.getElementById("selectedChoicesText").innerText = selectedChoices.toString();
}

function checkAll() {
   var chboxArray = document.getElementsByName("priority");
   for (var i = 0; i < chboxArray.length; i++) {
      chboxArray[i].checked = true;
   selectedChoices = selectedChoices.filter(function(e){return e!==chboxArray[i].id})//remove existing item first
   selectedChoices.push(chboxArray[i].id);
   }
   document.getElementById("selectedChoicesText").innerText = selectedChoices.toString();
}

function uncheckAll() {
   var chboxArray = document.getElementsByName("priority");
   for (var i = 0; i < chboxArray.length; i++) {
      chboxArray[i].checked = false;
   selectedChoices = [];
 }
   document.getElementById("selectedChoicesText").innerText = selectedChoices.toString();
}

function operationForSelected(){
 document.getElementById("selectedChoices").value = selectedChoices.toString();
}

</script>

</body>
</html>