1、使用的插件:
(1) select2-3.5.2/select2.min.js
(2) jquery.validate.bootstrap.popover.js、jquery.validate.min.js
2、应用环境
首先看一下设计需求(见下图):
页面中“Select one or more branch”处可以多选,使用的是select2插件,这里真正的select被隐藏,并且需要验证(当且仅当By Branch地单选框被选中,且未选择branch时,给出错误提示)。而右侧CCM Permissions下的Manage CCM的复选框下也存在隐藏输入框,并且只在显示时需要验证。如下图
3、编码分析(后台php,框架CI3)
关键HTML代码如下:
<div class="form-group">
<?php echo form_label('Location Assignment', '', array('class' => 'control-label')); ?>
<div class="control-label">
<label class="radio-inline">
<input type="radio" name="sub_type" value="0" checked>
To all locations
</label>
<label class="radio-inline">
<input type="radio" name="sub_type" id="sub_type" value="1">
By Branch
</label>
</div>
</div>
<div id= "sub_branch" class="form-group hide">
<?php echo form_label('Branches', '', array('class'=>'control-label'));?>
<select id="branches" name="branches[]" multiple="multiple" style="width: 100%" >
<?php foreach ($branches as $branch): ?>
<option value="<?php echo $branch->id; ?>"><?php echo $branch->branch_name; ?></option>
<?php endforeach ?>
</select>
</div>
jQuery代码设计:
<script type="text/javascript">
$(document).ready(function() {
$('#branches').select2({
placeholder: "Select one or more branch",
});
var sub_type = $('input[name=sub_type]:checked').val();
if (sub_type == 1) {
$('#sub_branch').removeClass('hide');
} else {
$('#sub_branch').removeClass('hide').addClass('hide');
}
$('input[name=sub_type]').on('change', function(event) {
if(this.value == 1) {
$('#sub_branch').removeClass('hide');
} else {
$('#sub_branch').removeClass('hide').addClass('hide');
}
});
jQuery.validator.addMethod("required2", function(value, element){
return !$("#sub_type").is(":checked") || ($(element).val() ? true : false);
});
$("#form-create-user").validate_popover({
rules: {
"branches[]": { //多选select,使用branches[],并且用双引号""括起来。
required2: true,
}
},
messages: {
"branches[]": {
required2: "<?php echo lang('location_branch_required'); ?>",
}
},
popoverPosition: 'top',
ignore: ".ignore", //仅对.ignore类的对象忽略验证,对隐藏对象进行验证
hideForInvisible: false,
get_offset_element: function(element) {//重新定位隐藏对象的位置
if ($(element).is(":hidden")) {
return $(element).prev('div');
} else {
return $(element);
}
},
submitHandler: function(form) {
$('#btn-create-user').attr('disabled', 'disabled');
$('#form-create-user').prepend('<div id="processing-msg" class="alert alert-info"><?php echo lang("message_processing"); ?></div>');
form.submit();
}
});
});
</script>
4、注意问题
在使用对select2下拉框进行required验证时,还要注意下拉框的缺省值不要写成0=>'xxx',而要写成
$branch_options = array('' => '--SELECT--');