【发布时间】:2018-09-15 09:41:51
【问题描述】:
我有一个视图,其中有一些单选按钮,每个按钮对应于数据库中存在的一个帖子。下面还有一个单选按钮来创建新帖子“创建新帖子”。当页面被访问时,“创建新帖子”单选按钮被选中,因此下面的其他表单字段为空
问题:当用户选择某个与现有帖子对应的单选按钮时,表单字段将使用下面的 jQuery 填充数据库中存储的帖子信息。如果用户更改表单的某些信息,例如日期字段,并引入格式不正确的日期并提交表单,则会出现错误,但“创建帖子”单选按钮被选中,因此而不是用户继续在编辑所选帖子的上下文中,他更改为创建新帖子的上下文,因为单选按钮“创建新帖子”被选中。
你知道如何解决这个问题吗?
带有每个帖子单选按钮和“创建新帖子”单选按钮和其他表单字段的表单:
<p>{{$anyPost}}-aaaaa</p>
<form id="editposts" method="post"
action="{{route('posts.update', ['post_id' => $post->id])}}" enctype="multipart/form-data">
{{csrf_field()}}
<div>
@foreach($posts as $post)
<div class="form-check">
<input {{ (old('radiobutton') && old('radiobutton') == $post->id) ? 'checked' : '' }} class="form-check-input radio" type="radio" name="radiobutton" value="{{ $post->id }}" id="{{$post->id}}">
<label class="form-check-label">
{{$post->title}}
</label>
</div>
@endforeach
</div>
<div class="form-check">
<input checked checked {{ (old('radiobutton') && old('radiobutton') == 'create_post') ? 'checked' : '' }} class="form-check-input" type="radio" name="radiobutton" id="create_post"
value="create_post">
<label class="form-check-label">
Create post
</label>
</div>
<!-- form fields, here is the name but are more like description, etc -->
<div class="form-group">
<label>Post title</label>
<input type="text" required class="form-control" value="{{ old('title') }}" name="title" id="tile">
</div>
<input type="submit" id="poststore" value="Create"/>
<input type="submit" id="postupdate" value="Update"/>
</form>
JS 根据所选帖子填充表单字段并根据所选单选按钮更改表单操作:
var posts = {!! $post !!}
$("#postupdate").hide();
$("input[name='radiobutton']").click(function() {
let id = $(this).attr("id");
if (id == "create_post") {
$("#postupdate").hide();
$("#poststore").show();
$("#editposts").attr('action', '{{route('posts.store', ['post_id' => $post->id])}}');
$("input[name='title']").val("");
...
} else {
$("#postupdate").show();
$("#poststore").hide();
$("#editposts").attr('action', '{{route('posts.update', ['post_id' => $post->id])}}');
let data = posts.find(e => e.id == id) || {
title: "",
...
};
$("input[name='title']").val(data.title);
...
}
});
我在控制器中有这个“->with('anyPost', $isAnyPostButtonChecked);”要调试,表单上方有“<p>{{$anyPost}}-aaaaa</p>”,但在提交表单之前和之后它总是显示为假。
public function edit($id)
{
...
$isAnyPostButtonChecked = false;
$isAnyPostButtonChecked = $isAnyPostButtonChecked && (old('radiobutton') && old('radiobutton') == $post->id);
return view('posts.edit')
->with('posts', $post)
->with('anyPost', $isAnyPostButtonChecked);
}
“{{var_dump(old('radiobutton')}}”显示:
空
【问题讨论】:
-
请使用 sn-p 直观地重现问题,这样您更有可能获得帮助
-
谢谢,但问题包括 php 代码,因为用户正在更新帖子并提交表单,如果出现验证错误,选中的单选按钮是“创建帖子”单选按钮,所以这个问题,它不仅包括 jquery 和 html 的 php 代码。
-
checked checked重复 -
哪个单选按钮没有被选中?一个输入应该只有一个选中的属性,这个
{{ (old('radiobutton') && old('radiobutton') == 'create_post') ? 'checked' : '' }}。我认为您的 laravel 验证没有传递所需的值。 -
什么是 $event->id
标签: javascript php jquery html laravel