我有一个长而复杂的形式,有几个条件的'字段 - 字段B仅显示字段A是否标记为'是'例如。
这是HTML:
<div class="{{ $errors->has('happy') ? ' has-error' : false }}">
{{Form::label('happy', 'Are you happy?')}}
{{Form::select('happy', array('' => '--', 'Yes' => 'Yes', 'No' => 'No'),(!empty($input['happy']) ? $input['happy'] : null), ['class'=>'dependent']);}}
</div>
<div class="{{ !empty($input['happy']) && $input['happy'] == 'Yes' ? null : 'hidden'}} dependent" data-dependent-field="happy" data-dependent-value="Yes">
{{Form::label('second-field', 'Only asked if you\'re happy')}}
{{Form::textarea('second-field',!empty($input['second-field']) ? $input['second-field'] : null)}}
</div>
问题在于,如果第二个字段中存在验证错误,则提交表单时,原始输入未被识别且hidden
类仍在添加到第二个字段中一组字段。
{{ !empty($input['happy']) && $input['happy'] == 'Yes' ? null : 'hidden'}}
该代码在重新加载包含要编辑的数据的表单时起作用,但在发送验证错误时则不起作用。验证码如下所示:
if($validation->fails()){
return Redirect::back()->withInput()->withErrors($validation->errors())->with(['flash_message'=>'Please check your inputs again.']);
}
我猜测我没有正确引用退货数据,但无法弄清楚我出错的地方。
我已经在更改输入时使用jQuery扩展字段,但在验证错误后重新加载时,这并不会处理字段。
编辑更多CLAIRTY:
这是一个例子。如果我选择是,那么请离开“为什么”#39;回答空白并且它是必填字段,当Laravel执行back()->withErrors()
位时,文本区域不会显示在屏幕上。
<div class="row {{ $errors->has('happy') ? ' has-error' : false }}">
{{Form::label('happy', 'Field Label', ['class'=>'span12'])}}
<div class="span3">
{{Form::select('happy', array('' => '--', 'Yes' => 'Yes', 'No' => 'No'),(!empty($input['happy']) ? $input['happy'] : null), ['class'=>'dependent']);}}
</div>
</div>
<div class="row">
<div class="span12">
<div class="{{ !empty($input['happy']) && $input['happy'] == 'No' ? null : 'hidden'}} dependent" data-dependent-field="happy" data-dependent-value="No">
<div {{ $errors->has('why-not-happy') ? ' has-error' : false }}">
{{Form::label('why-not-happy', 'Why aren\'nt you happy?')}}
{{Form::textarea('why-not-happy',!empty($input['why-not-happy']) ? $input['why-not-happy'] : null)}}
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
问题的一个解决方案是它可以通过jQuery解决,因为这是您在提交表单之前需要实现的。 $ input ['happy']仅在您提交后才会获得值。
回到找到问题的解决方案。
您可以在视图末尾或单独的.js文件中将其包含为摘录。
jQuery代码可以如下:
<script type='text/javascript'>
$(function() {
//you may assign an id to the dropdown, just in case, and mention it as a selector
$('select.dependent').change(function(d){
d.preventDefault();
var selectValue = this.val();
if(selectValue !='happy' || selectValue.length === 0){
//Whatever you want to achieve when the selected value is NOT happy or empty
$('div.dependent').addClass('hidden');
}
});
});
</script>
我希望它有所帮助。如果没有,请告诉我。