使用 jquery 验证克隆的复选框和单选按钮
Posted
技术标签:
【中文标题】使用 jquery 验证克隆的复选框和单选按钮【英文标题】:Validate cloned checkboxes and radio buttons using jquery 【发布时间】:2017-04-30 16:28:13 【问题描述】:我正在尝试使用 JQuery 验证克隆的表单元素。以下是我的代码:
html:
<form class="form-inline">
<div class="panel panel-default">
<div class="panel panel-heading">
Yii2 Form Clone Html
<a href="#" class="add btn btn-sm btn-success pull-right">Add</a>
</div>
<div class="panel panel-body">
<div class="form-section">
<div class="row" style="margin-top: 20px;">
<div class="col-md-3">
<div class="form-group">
<input type="text" class="name form-control" placeholder="Username" id="name" name="username[]">
<span class="error"></span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<select name="city[]" class="form-control" class="city" id="city">
<option value="">Select City</option>
<option value="Pune">Pune</option>
<option value="Mumbai">Mumbai</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="checkbox-inline">
<input type="checkbox" class="edu" value="MBA" name="edu[0]" id="edu"> MA
</label>
<label class="checkbox-inline">
<input type="checkbox" class="edu" value="MA" name="edu[0]" id="edu"> MA
</label>
<span class="error"></span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="radio-inline">
<input type="radio" name="gender[0]" id="gender" value="Male" class="gender"> Male
</label>
<label class="radio-inline">
<input type="radio" name="gender[0]" id="gender" value="Female" class="gender"> Female
</label>
<span class="error"></span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="file" placeholder="Name" name="photo[]" id="photo" class="photo">
<span class="error"></span>
</div>
</div>
</div>
</div>
</div>
</div>
<input type="submit" name="submit" value="Submit" class="submit btn btn-primary">
</form>
JQuery 代码:
$(document).ready(function ()
//Create a variable "clonedTemplate"
var clonedTemplate = $(".form-section .row:first").clone();
var removeLink = "<div class='col-md-1'><div class='form-group pull-right'><a href='#' class='btn btn-sm btn-danger delete'>x</a></div></div>";
var index = 0;
$("body").on('click', '.add', function ()
index++;
var formSection = clonedTemplate.clone().find(':input').each(function ()
var oldId = $(this).attr('id'); // getting "id" attribute
var newId = oldId + "_" + index; // generating new id
$(this).attr('id', newId); // updating "id" field
if ($(this).attr('type') === "radio")
var prefix = "gender[" + index + "]";
$(this).attr('name', prefix); // updating "name" field
if ($(this).attr('type') === "checkbox")
var prefix = "edu[" + index + "]";
$(this).attr('name', prefix); // updating "name" field
);
formSection.end().appendTo('.form-section');
$(".form-section .row:last").append(removeLink);
);
$("body").on("click", ".delete", function ()
$(this).closest(".row").remove();
);
$("body").on("click", ".submit", function ()
$(".form-section").find(":input").each(function (i)
var type = $(this).attr('type');
//console.log(type);
var errorTag = $(this).closest('.form-group').find('.error');
var val = $(this).val();
switch (type)
case "text":
if (val === "")
errorTag.html("Username cannot be blank.");
else
errorTag.html("");
break;
case "file":
if (val === "")
errorTag.html("Photo cannot be blank.");
else
errorTag.html("");
break;
case "radio":
if ($(this).closest(".gender").prop('checked') !== true)
errorTag.html("Gender cannot be blank.");
else
errorTag.html("");
break;
case "checkbox":
if ($(this).closest(".edu").prop('checked') !== true)
errorTag.html("Education cannot be blank.");
else
errorTag.html("");
break;
default:
$(this).val("");
);
return false;
);
);
我在验证克隆的单选按钮和复选框时遇到问题。它仅在我选择所有单选按钮/复选框或最后一个时才有效。如果我选择第一个单选按钮/复选框,则显示验证错误。
我正在使用 jquery closest()
here 来逐行验证它,因为在单击“添加”按钮后表单正在被克隆(添加行)。
检查以下小提琴:
https://jsfiddle.net/KJO/6vLdzzq4/2/
任何帮助将不胜感激。
【问题讨论】:
【参考方案1】:我稍微修改了你的代码,
在你的 switch 语句中修改了复选框和单选按钮的情况,
(我认为您验证表单的方法不是最佳解决方案)
$(document).ready(function()
//Create a variable "clonedTemplate"
var clonedTemplate = $(".form-section .row:first").clone();
var removeLink = "<div class='col-md-1'><div class='form-group pull-right'><a href='#' class='btn btn-sm btn-danger delete'>x</a></div></div>";
var index = 0;
$("body").on('click', '.add', function()
index++;
var formSection = clonedTemplate.clone().find(':input').each(function()
var oldId = $(this).attr('id'); // getting "id" attribute
var newId = oldId + "_" + index; // generating new id
$(this).attr('id', newId); // updating "id" field
if ($(this).attr('type') === "radio")
var prefix = "gender[" + index + "]";
$(this).attr('name', prefix); // updating "name" field
if ($(this).attr('type') === "checkbox")
var prefix = "edu[" + index + "]";
$(this).attr('name', prefix); // updating "name" field
);
formSection.end().appendTo('.form-section');
$(".form-section .row:last").append(removeLink);
);
$("body").on("click", ".delete", function()
$(this).closest(".row").remove();
);
$("body").on("click", ".submit", function()
var radioChecked = false;
$(".form-section").find(":input").each(function(i)
var type = $(this).attr('type');
//console.log(type);
var errorTag = $(this).closest('.form-group').find('.error');
var val = $(this).val();
switch (type)
case "text":
if (val === "")
errorTag.html("Username cannot be blank.");
else
errorTag.html("");
break;
case "file":
if (val === "")
errorTag.html("Photo cannot be blank.");
else
errorTag.html("");
break;
case "radio":
if (!$("input[name='" + $(this).attr('name') + "']:checked").val())
errorTag.html("Gender cannot be blank.");
else
errorTag.html("");
break;
case "checkbox":
if (!$("input[name='" + $(this).attr('name') + "']:checked").val())
errorTag.html("Education cannot be blank.");
else
errorTag.html("");
break;
default:
$(this).val("");
);
return false;
);
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body-content">
<form class="form-inline">
<div class="panel panel-default">
<div class="panel panel-heading">
Yii2 Form Clone Html
<a href="#" class="add btn btn-sm btn-success pull-right">Add</a>
</div>
<div class="panel panel-body">
<div class="form-section">
<div class="row" style="margin-top: 20px;">
<div class="col-md-3">
<div class="form-group">
<input type="text" class="name form-control" placeholder="Username" id="name" name="username[]">
<span class="error"></span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<select name="city[]" class="form-control" class="city" id="city">
<option value="">Select City</option>
<option value="Pune">Pune</option>
<option value="Mumbai">Mumbai</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="checkbox-inline">
<input type="checkbox" class="edu" value="MBA" name="edu[0]" id="edu">MA
</label>
<label class="checkbox-inline">
<input type="checkbox" class="edu" value="MA" name="edu[0]" id="edu">MA
</label>
<span class="error"></span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="radio-inline">
<input type="radio" name="gender[0]" id="gender" value="Male" class="gender">Male
</label>
<label class="radio-inline">
<input type="radio" name="gender[0]" id="gender" value="Female" class="gender">Female
</label>
<span class="error"></span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<input type="file" placeholder="Name" name="photo[]" id="photo" class="photo">
<span class="error"></span>
</div>
</div>
</div>
</div>
</div>
</div>
<input type="submit" name="submit" value="Submit" class="submit btn btn-primary">
</form>
</div>
【讨论】:
更改对我有用。谢谢 :) 但是,如果您能解释一下我的代码出了什么问题以及验证克隆表单的更好方法应该是什么,那就太好了。 我说“不是最佳的”,因为你要检查每个复选框和单选按钮以检查至少一个被选中,这就是为什么 是的,但我使用closest()
方法来验证复选框和单选按钮行明智。【参考方案2】:
1、使用:check
查询
虽然这种方式性能不好。 $(".gender:checked") 将返回所有已检查的 .gender 电台。
case "radio":
if ($(".gender:checked").length == 0)//no radio checked.
errorTag.html("Gender cannot be blank.");
else
errorTag.html("");
break;
https://jsfiddle.net/6vLdzzq4/3/
2、序列化
如果您想重新编写代码,可以尝试使用 Jquery 序列化表单数据,然后根据结果进行验证
var serialized= $('.form-inline').serializeArray();
console.log(serialized);
-> Array[ Object, Object]
如果选中了任何复选框或单选框,则具有给定名称的对象将出现在 serialized
中。
【讨论】:
以上是关于使用 jquery 验证克隆的复选框和单选按钮的主要内容,如果未能解决你的问题,请参考以下文章