我有一个使用Chosen插件和jQuery Validate插件的场景,我试图根据单选按钮选中的选项显示和隐藏字段。因此,我也在尝试验证它们。这是我的代码:
<form id="my-form" action="" method="post">
<input type="radio" name="active" id="1" value="1" onclick="test(1)" > A
<input type="radio" name="active" id="1" value="2" onclick="test(2)"> B
<input type="radio" name="active" id="1" value="3" onclick="test(3)"> C
<input type="radio" name="active" id="1" value="4" onclick="test(4)" checked> D
<div class='with-select' id="resident" style="display:none !important;">
<span>resident:</span>
<select class="chosen-select" required="true">
<option value="">[select option]</option>
<option value="01">Value 1</option>
<option value="02">Value 2</option>
<option value="03">Value 3</option>
<option value="04">Value 4</option>
<option value="05">Value 5</option>
</select>
</div>
<div class='with-select' id="employee" style="display:none !important;">
<span>employee:</span>
<select class="chosen-select" name="selEmp" id="selEmp" required="true">
<option value="">[select option]</option>
<option value="01">Value 1</option>
<option value="02">Value 2</option>
<option value="03">Value 3</option>
<option value="04">Value 4</option>
<option value="05">Value 5</option>
</select>
</div>
<div class='with-select' id="inputvis" style="display:none !important;">
<span>Visitor:</span>
<input type="text" name="txtVis" id="txtVis" required="true">
</div>
<div class='with-select' id="inputothr" >
<span>Other:</span>
<input type="text" name="txtOther" id="txtOther" required="true">
</div>
<div>
<input type="submit" />
</div>
</form>
<script>
// Chosen validation
$('.chosen-select').chosen();
$.validator.setDefaults({ ignore: ":hidden:not(select)" });
// validation of chosen on change
if ($("select.chosen-select").length > 0) {
$("select.chosen-select").each(function() {
if ($(this).attr('required') !== undefined) {
$(this).on("change", function() {
$(this).valid();
});
}
});
}
// validation
$('#my-form').validate({
errorPlacement: function (error, element) {
console.log("placement");
if (element.is("select.chosen-select")) {
console.log("placement for chosen");
// placement for chosen
element.next("div.chzn-container").append(error);
} else {
// standard placement
error.insertAfter(element);
}
}
});
window.test = function(a){
//alert(a);
switch(a){
case 1:
$("#resident").show();
$("#employee").hide();
$("#inputvis").hide();
$("#inputothr").hide();
break;
case 2:
$("#resident").hide();
$("#employee").show();
$("#inputvis").hide();
$("#inputothr").hide();
break;
case 3:
$("#resident").hide();
$("#employee").hide();
$("#inputvis").show();
$("#inputothr").hide();
break;
case 4:
$("#resident").hide();
$("#employee").hide();
$("#inputvis").hide();
$("#inputothr").show();
break;
}
}
</script>
问题是我必须在每个字段中选择/输入值才能发布表单。我如何才能发布表单并选中一个单选按钮,然后仅在对应的那个字段(其他)中输入值,然后跳过对其他选择框或遗漏的任何内容的验证?