我有一张表格。在此,用户从单选按钮中选择一个值。从所有问题我只能选择一个答案。但是循环应该允许从每个问题中选择一个答案。
<form method="POST" action="{{url('quiz/check')}}"
{!! csrf_field() !!}
@foreach ($quiz as $q)
{{ $q->qid }}.
{{ $q->question }}<br>
<input type='radio' name='mycheck[".$q->qid."]' value='1'>
{{ $q->opt1 }}<br>
<input type='radio' name='mycheck[".$q->qid."]' value='2'>
{{ $q->opt2 }}<br>
<input type='radio' name='mycheck[".$q->qid'."]' value='3'>
{{ $q->opt3 }}<br>
<input type='radio' name='mycheck[".$q->qid'."]' value='4'>
{{ $q->opt4 }}<br><br>
@endforeach
<button type="submit" class="btn btn-default">Get result</button>
</form>
将表单重定向到此控制器。
public function check(Request $request)
{
$count=0;
$input=$request->all();
$ch = DB::select('select * from quiz where category="gk" ');
return View('quiz.check',['quiz'=>$ch,'input'=>$input,'count'=>$count]);
}
我有$ count变量0.每个正确答案应该增加1。
查看:quiz.check
@foreach ($quiz as $q)
@if($input['mycheck'][$q->qid]==$q->answer)
{
$count=$count+1;
}
@endif
@endforeach
You scored {{$count}}.
答案 0 :(得分:0)
你必须这样使用:
<form method="POST" action="{{url('quiz/check')}}"
{!! csrf_field() !!}
@foreach ($quiz as $q)
{{ $q->qid }}.
{{ $q->question }}<br>
<input type='radio' name='mycheck_{{$q->qid}}' value='1'>
{{ $q->opt1 }}<br>
<input type='radio' name='mycheck_{{$q->qid}}' value='2'>
{{ $q->opt2 }}<br>
<input type='radio' name='mycheck_{{$q->qid}}' value='3'>
{{ $q->opt3 }}<br>
<input type='radio' name='mycheck_{{$q->qid}}' value='4'>
{{ $q->opt4 }}<br><br>
@endforeach
<button type="submit" class="btn btn-default">Get result</button>
</form>
答案 1 :(得分:0)
这就是我应该做的事情。
<input type='radio' name='mycheck[{{$q->qid}}]' value='1'>
在控制器中:
public function check(Request $request)
{
$count=0;
$input=$request->all();
$mycheck=$input['mycheck'];
$ch = DB::select('select * from quiz where category="gk" ');
return View('quiz.check',['quiz'=>$ch,'input'=>$input,'count'=>$count,'mycheck'=>$mycheck]);
}
在视图中:
@foreach ($quiz as $q)
@if(array_key_exists($q->qid, $mycheck) && $mycheck[$q->qid]==$q->answer)
{{$count=$count+1}}
@endif
@endforeach
You scored {{$count}}.