gpt4 book ai didi

javascript - 如果存在验证错误,则保持检查单选按钮无法正常工作

转载 作者:行者123 更新时间:2023-12-03 02:11:37 27 4
gpt4 key购买 nike

我有一个 View ,其中显示一些单选按钮,每个按钮对应于数据库中存在的一篇文章。下面还有一个用于创建新帖子的单选按钮“创建新帖子”。当访问该页面时,“创建新帖子”单选按钮被选中,因此下面的其他表单字段为空。

当单击与现有帖子相对应的单选按钮时,表单字段将填充该帖子信息。单击单选按钮“创建新帖子”时,表单字段将变为空,以便用户可以引入信息来创建新帖子。

如果用户选择单选按钮“创建帖子”并填写表单字段并单击“创建”,并且他错误地填写了某些字段,例如日期格式不正确,则这些字段不会被清除,因此用户不需要再次介绍它们,“创建新帖子”单选按钮仍处于选中状态。这工作得很好。

问题:但是,当用户选择与现有帖子相对应的某个单选按钮时,表单字段将使用 JS 填充数据库中的帖子存储信息。如果用户更改表单的某些信息,例如日期字段,并引入格式不正确的日期,则会出现错误,但“创建帖子”单选按钮会被选中,因此用户不会继续在他将编辑所选帖子的上下文更改为创建新帖子的上下文,因为单选按钮“创建新帖子”被选中。

你知道如何解决这个问题吗?

包含每个帖子单选按钮和“创建新帖子”单选按钮以及其他表单字段的表单:

<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);
...
}
});

最佳答案

默认情况下,您已双重选中单选按钮:

<input checked checked {{ (old('radiobutton') && old('radiobutton') == 'create_post') ? 'checked' : '' }} class="form-check-input" type="radio" name="radiobutton" id="create_post"

删除它并更改为:

<input {{ (old('radiobutton') && old('radiobutton') == 'create_post') ? 'checked' : '' }} class="form-check-input" type="radio" name="radiobutton" id="create_post"

关于javascript - 如果存在验证错误,则保持检查单选按钮无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49537904/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com