选择至少一个复选框的Jquery验证

时间:2016-09-30 06:35:31

标签: jquery validation checkboxlist

enter image description here

我想验证必须至少选中一个复选框,否则显示错误和焦点。这是我的表格:

<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> 

以下是我的尝试:

//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"});
}

1 个答案:

答案 0 :(得分:2)

这里有一个代码供你开始......

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" />