Abdul Waheed Abdul Waheed - 2 months ago 6
jQuery Question

Jquery validation for select at least one check box

enter image description herei want to validate at least one checkbox has to be selected or else show error and focus.
Here is my form:

<div class="form-group">Eligible Branch
<select id="eligiblebranch" multiple="multiple" class="form-control" >
<?php $branch = $conn->query("SELECT * FROM r_branch ORDER BY id_branch ASC");
while ($branchresult = $branch->fetch_assoc()) { ?>
<option value="<?php echo $branchresult['id_branch']; ?>"> <?php echo $branchresult['branch_name']; ?> </option>
<?php } ?>
</select>
</div>


And here what have tried:

//Eligible branch
var eligiblebranch = $("#eligiblebranch").val();
if(eligiblebranch=='0')
{
$("#eligiblebranch").css({"border-style": "solid", "border-color": "red"});
$("#showMessage").html('Please Enter Eligible Branch');
$("#eligiblebranch").focus();
return false;
}else{
$("#eligiblebranch").css({"border-style": "solid","border-color": "#E9E9E9"});
}

Answer

Here a code for you to start with...

function validate(){
var gR = $("#eligiblebranch :checked");
  if(gR.length==0){
    alert("Please select atleast one option");
  } else {
    alert("Can submit form");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">Eligible Branch
    <select id="eligiblebranch" multiple="multiple" class="form-control" >
        <option value="A">A</option>
      <option value="B">B</option>
      <option value="BB">BB</option>
      <option value="AA">AA</option>
    </select>
</div>
<input type="button" onclick="validate()" value="Submit" />