我有多个动态下拉列表,我正在通过jquery所需的验证器进行验证。但问题是下拉列表从 0 索引开始,因此在选择选择时验证不起作用。我正在使用以下代码。
jQuery('form#add_form :input').each(function(){
jQuery(this).rules('add', {
required: function(element) {
if(element.type=='select') {
if(jQuery(this).children('option:selected').val() == '0')
{
return false;
}
else
{
return true;
}
} else
{
return true;
}
} });
});
表单标签 :
{{Form::open(array('','method' => 'post','class'=>'add-form','id'=>'add_form')) }}
@foreach($parent_attrs as $pattr)
<div class="col-md-6">
<label>
{!! Form::select('product'.$pattr->id, $products, $pattr, ['class' => 'form-control']) !!}
</div>
@endforeach
这是一个片段。
$('form#add_form').validate();
$('select').each(function () {
$(this).rules('add',{
required_select: true
});
});
$.validator.addMethod('required_select', function(value, element) {
return value > 0;
}, 'Please choose a option');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<form id="add_form" method="post" action="" >
<select id="product_1" name="product_1">
<option value="0">Select Product 1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="product_2" name="product_2">
<option value="0">Select Product 2</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button type="submit" name="submit"> Submit </button>
</form>
希望这对:)有所帮助