动态创建或删除表单元素
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态创建或删除表单元素相关的知识,希望对你有一定的参考价值。
我正在创建一个Dynamic Form Elements
,我必须添加多个家属。
我的代码如下。
在我的项目中,我必须添加至少一个我使用html创建的依赖项,但是允许用户添加用户想要的内容,因此我使用jQuery并动态创建相同的表单,单击用户按钮,用户也可以选择删除它。
我已经应用了一些验证,在添加新的依赖项之前,用户必须在点击Add Dependant
按钮时填写所有字段。此外,在Add Dependant
按钮上,我只是使用计数器验证以前的表单。
我正在使用Counter
变量并使用它检查最后添加的表单,并在用户创建表单时递增它,并且在删除时我只是递减它。
在Next
按钮上,我正在验证整个表单控件,因为用户可能已删除或将任何字段留空,因此我在点击下一步按钮时检查这一点。
问题是当加起来2个或2个以上的表格然后我删除中间的一个或第二个,Add Dependant
和Next
按钮停止做任何事情,这导致我的问题。我希望这个表格像用户可以随时添加和删除。
我怎样才能做到这一点?
var counter = 0;
var regexDoB = new RegExp('([0-9][1-2])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2})');
$("#btAdd").on('click', function(e) {
e.preventDefault();
$('#errorDepFirstName' + counter).html("");
$('#errorDepLastName' + counter).html("");
$('#errorDepDateOfBirth' + counter).html("");
$('#errorDepGender' + counter).html("");
$('#errorDepRelationship' + counter).html("");
if ($('#txtDepFirstName' + counter).val() == '') {
$('#errorDepFirstName' + counter).html("Please provide Dependent's First Name");
$('#txtDepFirstName' + counter).focus();
return false;
} else if ($('#txtDepLastName' + counter).val() == '') {
$('#errorDepLastName' + counter).html("Please provide Dependent's Last Name");
$('#txtDepLastName' + counter).focus();
return false;
} else if ($('#txtDepDateOfBirth' + counter).val() == '') {
$('#errorDepDateOfBirth' + counter).html("Please provide Dependent's Date of Birth");
$('#txtDepDateOfBirth' + counter).focus();
return false;
} else if (!regexDoB.test($('#txtDepDateOfBirth' + counter).val())) {
$('#errorDepDateOfBirth' + counter).html("Invalid Dependent's Date of Birth");
$('#txtDepDateOfBirth' + counter).focus();
return false;
} else if ($('#ddDepGender' + counter).val() == -1) {
$('#errorDepGender' + counter).html("Please select Dependent's Gender");
$('#ddDepGender' + counter).focus();
return false;
} else if ($('#ddDepRelationship' + counter).val() == -1) {
$('#errorDepRelationship' + counter).html("Please select relation with Dependent");
$('#ddDepRelationship' + counter).focus();
return false;
} else if ($('#ddDepRelationship' + counter).val() == 'CH' && getAge($('#txtDepDateOfBirth' + counter).val()) > 25) {
$('#errorDepDateOfBirth' + counter).html("Child Dependent's must be age 25 or younger");
$('#txtDepDateOfBirth' + counter).focus();
return false;
} else {
var div = GetDynamicTextBox();
$("#TextBoxContainer").append(div);
}
});
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
$("#btnNext").on('click', function(e) {
e.preventDefault();
for (var j = 0; j <= counter; j++) {
$('#errorDepFirstName' + j).html("");
$('#errorDepLastName' + j).html("");
$('#errorDepDateOfBirth' + j).html("");
$('#errorDepGender' + j).html("");
$('#errorDepRelationship' + j).html("");
}
flag = true;
for (var i = 0; i <= counter; i++) {
if ($('#txtDepFirstName' + i).val() == '') {
$('#errorDepFirstName' + i).html("Please provide Dependent's First Name");
$('#txtDepFirstName' + i).focus();
flag = false;
} else if ($('#txtDepLastName' + i).val() == '') {
$('#errorDepLastName' + i).html("Please provide Dependent's Last Name");
$('#txtDepLastName' + i).focus();
flag = false;
} else if ($('#txtDepDateOfBirth' + i).val() == '') {
$('#errorDepDateOfBirth' + i).html("Please provide Dependent's Date of Birth");
$('#txtDepDateOfBirth' + i).focus();
flag = false;
} else if (!regexDoB.test($('#txtDepDateOfBirth' + i).val())) {
$('#errorDepDateOfBirth' + i).html("Invalid Dependent's Date of Birth");
$('#txtDepDateOfBirth' + i).focus();
flag = false;
} else if ($('#ddDepGender' + i).val() == -1) {
$('#errorDepGender' + i).html("Please select Dependent's Gender");
$('#ddDepGender' + i).focus();
flag = false;
} else if ($('#ddDepRelationship' + i).val() == -1) {
$('#errorDepRelationship' + i).html("Please select relation with Dependent");
$('#ddDepRelationship' + i).focus();
flag = false;
} else if ($('#ddDepRelationship' + i).val() == 'CH' && getAge($('#txtDepDateOfBirth' + counter).val()) > 25) {
$('#errorDepDateOfBirth' + i).html("Child Dependent's must be age 25 or younger");
$('#txtDepDateOfBirth' + i).focus();
flag = false;
}
}
if (flag == true) {
alert("No Error Found, Redirecting");
//submission of data
}
});
$("body").on("click", ".removeitem", function(e) {
e.preventDefault();
counter--;
$(this).parent().parent().remove();
});
function GetDynamicTextBox() {
counter = counter + 1;
var div = $("<div />");
div.attr("class", 'my-3 border border-dark rounded p-3');
var header = '<p class="lead font-weight-bold bg-light text-center p-1">Dependant Details<button class="removeitem btn btn-link text-danger float-right" type="button"><span class="fas fa-times"></span></button></p>';
var divFormRow = $("<div />");
divFormRow.attr("class", "form-row");
var divRow1Col1 = $("<div />");
divRow1Col1.attr("class", "form-group col-md-4");
//FirstName
var lblDepFName = $("<label />").attr("for", "txtDepFirstName" + counter);
lblDepFName.attr("class", "font-weight-bold small");
lblDepFName.html("First Name");
var txtDepFName = $("<input />").attr("type", "text").attr("name", "DependentFName");
txtDepFName.attr("placeholder", "First Name").attr("class", "form-control dep-name");
txtDepFName.attr("id", "txtDepFirstName" + counter)
var errorDepFName = $('<span />');
errorDepFName.attr("class", "form-text text-danger small").attr("id", "errorDepFirstName" + counter);
divRow1Col1.append(lblDepFName);
divRow1Col1.append(txtDepFName);
divRow1Col1.append(errorDepFName);
divFormRow.append(divRow1Col1);
var divRow1Col2 = $("<div />");
divRow1Col2.attr("class", "form-group col-md-4");
//Middle Name
var lblDepMName = $("<label />").attr("for", "txtDepMiddleName" + counter);
lblDepMName.attr("class", "font-weight-bold small");
lblDepMName.html("Middle Name");
var txtDepMName = $("<input />").attr("type", "text").attr("name", "DependentMName");
txtDepMName.attr("placeholder", "Middle Name").attr("class", "form-control");
txtDepMName.attr("id", "txtDepMiddleName" + counter)
var errorDepMiddleName = $('<span />');
errorDepMiddleName.attr("class", "form-text text-danger small").attr("id", "errorDepMiddleName" + counter);
divRow1Col2.append(lblDepMName);
divRow1Col2.append(txtDepMName);
divRow1Col2.append(errorDepMiddleName);
divFormRow.append(divRow1Col2);
var divRow1Col3 = $("<div />");
divRow1Col3.attr("class", "form-group col-md-4");
//Last Name
var lblDepLName = $("<label />").attr("for", "txtDepLastName" + counter);
lblDepLName.attr("class", "font-weight-bold small");
lblDepLName.html("Last Name");
var txtDepLName = $("<input />").attr("type", "text").attr("name", "DependentLName");
txtDepLName.attr("placeholder", "Last Name").attr("class", "form-control");
txtDepLName.attr("id", "txtDepLastName" + counter)
var errorDepLastName = $('<span />');
errorDepLastName.attr("class", "form-text text-danger small").attr("id", "errorDepLastName" + counter);
divRow1Col3.append(lblDepLName);
divRow1Col3.append(txtDepLName);
divRow1Col3.append(errorDepLastName);
divFormRow.append(divRow1Col3);
var divRow2Col1 = $("<div />");
divRow2Col1.attr("class", "form-group col-md-4");
//Date of Birth
var lblDepDateOfBirth = $("<label />").attr("for", "DepDateOfBirth" + counter);
lblDepDateOfBirth.attr("class", "font-weight-bold small");
lblDepDateOfBirth.html('Date of Birth <span class="small">(MM/DD/YYYY)</span>');
var txtDepDateOfBirth = $("<input />").attr("type", "text").attr("name", "DependentDateOfBirth");
txtDepDateOfBirth.attr("placeholder", "MM/DD/YYYY").attr("class", "form-control");
txtDepDateOfBirth.attr("id", "txtDepDateOfBirth" + counter)
var errorDepDateOfBirth = $('<span />');
errorDepDateOfBirth.attr("class", "form-text text-danger small").attr("id", "errorDepDateOfBirth" + counter);
divRow2Col1.append(lblDepDateOfBirth);
divRow2Col1.append(txtDepDateOfBirth);
divRow2Col1.append(errorDepDateOfBirth);
divFormRow.append(divRow2Col1);
var divRow2Col2 = $("<div />");
divRow2Col2.attr("class", "form-group col-md-4");
//Gender
var lblDepGender = $("<label />").attr("for", "ddDepGender" + counter);
lblDepGender.attr("class", "font-weight-bold small");
lblDepGender.html("Gender");
var ddDepGender = $("<select></select>");
ddDepGender.attr("name", "DepGender").attr("class", "form-control");
ddDepGender.attr("id", "ddDepGender" + counter);
var optnGender = $('<option value="-1" selected="selected">Select Gender</option><option value="M">Male</option><option value="F">Female</option>');
ddDepGender.append(optnGender);
var errorDepGender = $('<span />');
errorDepGender.attr("class", "form-text text-danger small").attr("id", "errorDepGender" + counter);
divRow2Col2.append(lblDepGender);
divRow2Col2.append(ddDepGender);
divRow2Col2.append(errorDepGender);
divFormRow.append(divRow2Col2);
var divRow2Col3 = $("<div />");
divRow2Col3.attr("class", "form-group col-md-4");
//Relationship
var lblDepRelationship = $("<label />").attr("for", "ddDepRelationship" + counter);
lblDepRelationship.attr("class", "font-weight-bold small");
lblDepRelationship.html("Relationship to Primary Applicant");
var ddDepRelationship = $("<select></select>");
ddDepRelationship.attr("name", "DependantRelationship").attr("class", "form-control");
ddDepRelationship.attr("id", "ddDepRelationship" + counter);
var optnRelationship = $('<option value="-1" selected="selected">Select Relationship</option><option value="SP">Spouse or Domestic Partner</option><option value="CH">Child</option>');
ddDepRelationship.append(optnRelationship);
var errorDepRelationship = $('<span />');
errorDepRelationship.attr("class", "form-text text-danger small").attr("id", "errorDepRelationship" + counter);
divRow2Col3.append(lblDepRelationship);
divRow2Col3.append(ddDepRelationship);
divRow2Col3.append(errorDepRelationship);
divFormRow.append(divRow2Col3);
div.append(header);
div.append(divFormRow);
return div;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container mt-4">
<div id="DependentContainer">
<div id="TextBoxContainer" class="border rounded border-dark p-3 mb-3">
<div class="border rounded border-dark p-3">
<p class="lead font-weight-bold bg-light text-center p-1">
Dependant Details
</p>
<div class="form-row">
<div class="form-group col-md-4">
<label for="txtDepFirstName0" class="small font-weight-bold">
First Name</label>
<input type="text" class="form-control dep-name" id="txtDepFirstName0" name="DependentFName" placeholder="First Name" />
<span id="errorDepFirstName0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="txtDepMiddleName0" class="small font-weight-bold">
Middle Name</label>
<input type="text" class="form-control" id="txtDepMiddleName0" name="DependentMName" placeholder="Middle Name" />
<span id="errorDepMiddleName0" class="form-text text-danger"></span>
</div>
<div class="form-group col-md-4">
<label for="txtDepLastName0" class="small font-weight-bold">
Last Name</label>
<input type="text" class="form-control" id="txtDepLastName0" name="DependentLName" placeholder="Last Name" />
<span id="errorDepLastName0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="txtDepDateOfBirth0" class="small font-weight-bold">
Date of Birth <span class="small">(MM/DD/YYYY)</span></label>
<input type="text" class="form-control" id="txtDepDateOfBirth0" name="DependentDateOfBirth" placeholder="MM/DD/YYYY" />
<span id="errorDepDateOfBirth0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="ddDepGender0" class="small font-weight-bold">
Gender</label>
<select id="ddDepGender0" class="form-control" name="DepGender">
<option value="-1" selected="selected">Select Gender</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
<span id="errorDepGender0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="ddDepRelationship0" class="small font-weight-bold">
Relationship to Primary Applicant</label>
<select id="ddDepRelationship0" class="form-control" name="DependantRelationship">
<option value="-1" selected="selected">Select Relationship</option>
<option value="SP">Spouse or Domestic Partner</option>
<option value="CH">Child</option>
</select>
<span id="errorDepRelationship0" class="form-text text-danger small"></span>
</div>
</div>
</div>
<!--Textboxes will be added here -->
</div>
</div>
<div class="form-group text-center mt-3">
<input type="button" id="btAdd" value="Add Dependant" class="btn btn-primary" />
<br />
<input type="button" id="btnNext" value="Next" class="btn btn-primary float-right" />
</div>
<asp:Button Text="Save" ID="btnSave" CssClass="btn btn-danger btn-lg mt-5" OnClick="Process" runat="server" />
</div>
在jsFiddle上查看
正如其他人所提到的那样,在验证时,递减counter
会抛弃ID引用。
我建议使用类而不是ID。然后,您可以使用.form-row
或selector context
遍历每个find()
并验证每个块内的输入。像这样:
$('.errorFirstName', this)
这是一个演示:
var counter = 0;
var regexDoB = new RegExp('(0[1-9]|1[012])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2})');
function validateAll() {
// set to valid by default, in case no forms exist.
var valid = true;
// select all form blocks and errors
var $forms = $('.form-row');
var $errors = $('.text-danger', $forms);
// clear all errors
$errors.empty();
// iterate through all form blocks
$forms.each(function() {
// set block to invalid by default
valid = false;
// identify errors
if ($('.inputFirstName', this).val() == '') {
$('.errorFirstName', this).html("Please provide Dependent's First Name");
$('.inputFirstName', this).focus();
} else if ($('.inputLastName', this).val() == '') {
$('.errorLastName', this).html("Please provide Dependent's Last Name");
$('.inputLastName', this).focus();
} else if ($('.inputDOB', this).val() == '') {
$('.errorDOB', this).html("Please provide Dependent's Date of Birth");
$('.inputDOB', this).focus();
} else if (!regexDoB.test($('.inputDOB', this).val())) {
$('.errorDOB').html("Invalid Dependent's Date of Birth");
$('.inputDOB', this).focus();
} else if ($('.inputGender', this).val() == -1) {
$('.errorGender', this).html("Please select Dependent's Gender");
$('.inputGender', this).focus();
} else if ($('.inputRelationship', this).val() == -1) {
$('.errorRelationship', this).html("Please select relation with Dependent");
$('.inputRelationship', this).focus();
} else if ($('.inputRelationship', this).val() == 'CH' && getAge($('.inputDOB', this).val()) > 25) {
$('.errorDOB', this).html("Child Dependent's must be age 25 or younger");
$('.inputDOB', this).focus();
} else {
// set block to valid
valid = true;
}
// stop or continue block iteration
return valid;
});
// return validity state
return valid;
}
function GetDynamicTextBox() {
var div = $("<div>", {
'class': 'my-3 border border-dark rounded p-3'
});
var header = '<p class="lead font-weight-bold bg-light text-center p-1">Dependant Details<button class="removeitem btn btn-link text-danger float-right" type="button"><span class="fas fa-times"></span></button></p>';
var divFormRow = $("<div>", {
"class": "form-row"
});
//FirstName
var divRow1Col1 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepFName = $("<label>", {
"class": "font-weight-bold small",
"html": "First Name"
});
var txtDepFName = $("<input>", {
"type": "text",
"name": "DependentFName",
"placeholder": "First Name",
"class": "form-control inputFirstName"
});
var errorDepFName = $('<span>', {
"class": "form-text text-danger small errorFirstName"
});
lblDepFName.append(txtDepFName);
divRow1Col1.append(lblDepFName).append(errorDepFName);
divFormRow.append(divRow1Col1);
//Middle Name
var divRow1Col2 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepMName = $("<label>", {
"class": "font-weight-bold small",
"html": "Middle Name"
});
var txtDepMName = $("<input>", {
"type": "text",
"name": "DependentMName",
"placeholder": "Middle Name",
"class": "form-control inputMiddleName"
});
var errorDepMiddleName = $('<span>', {
"class": "form-text text-danger small errorMiddleName"
});
lblDepMName.append(txtDepMName);
divRow1Col2.append(lblDepMName).append(errorDepMiddleName);
divFormRow.append(divRow1Col2);
//Last Name
var divRow1Col3 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepLName = $("<label>", {
"class": "font-weight-bold small",
"html": "Last Name"
});
var txtDepLName = $("<input>", {
"type": "text",
"name": "DependentLName",
"placeholder": "Last Name",
"class": "form-control inputLastName"
});
var errorDepLastName = $('<span>', {
"class": "form-text text-danger small errorLastName"
});
lblDepLName.append(txtDepLName);
divRow1Col3.append(lblDepLName).append(errorDepLastName);
divFormRow.append(divRow1Col3);
//Date of Birth
var divRow2Col1 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepDateOfBirth = $("<label>", {
"class": "font-weight-bold small",
"html": 'Date of Birth <span class="small">(MM/DD/YYYY)</span>'
});
var txtDepDateOfBirth = $("<input>", {
"type": "text",
"name": "DependentDateOfBirth",
"placeholder": "MM/DD/YYYY",
"class": "form-control inputDOB"
});
var errorDepDateOfBirth = $('<span>', {
"class": "form-text text-danger small errorDOB"
});
lblDepDateOfBirth.append(txtDepDateOfBirth);
divRow2Col1.append(lblDepDateOfBirth).append(errorDepDateOfBirth);
divFormRow.append(divRow2Col1);
//Gender
var divRow2Col2 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepGender = $("<label>", {
"class": "font-weight-bold small",
"html": "Gender"
});
var ddDepGender = $("<select>", {
"name": "DepGender",
"class": "form-control inputGender"
});
var optnGender = $('<option value="-1" selected="selected">Select Gender</option><option value="M">Male</option><option value="F">Female</option>');
var errorDepGender = $('<span>', {
"class": "form-text text-danger small errorGender"
});
ddDepGender.append(optnGender);
lblDepGender.append(ddDepGender);
divRow2Col2.append(lblDepGender).append(errorDepGender);
divFormRow.append(divRow2Col2);
//Relationship
var divRow2Col3 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepRelationship = $("<label>", {
"class": "font-weight-bold small",
"html": "Relationship to Primary Applicant"
});
var ddDepRelationship = $("<select>", {
"name": "DependantRelationship",
"class": "form-control inputRelationship"
});
var optnRelationship = $('<option value="-1" selected="selected">Select Relationship</option><option value="SP">Spouse or Domestic Partner</option><option value="CH">Child</option>');
var errorDepRelationship = $('<span>', {
"class": "form-text text-danger small errorRelationship"
});
ddDepRelationship.append(optnRelationship);
lblDepRelationship.append(ddDepRelationship);
divRow2Col3.append(lblDepRelationship).append(errorDepRelationship);
divFormRow.append(divRow2Col3);
div.append(header);
div.append(divFormRow);
return div;
}
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
$("#btAdd").on('click', function(e) {
e.preventDefault();
var allValid = validateAll();
if (allValid) {
var div = GetDynamicTextBox();
$("#TextBoxContainer").append(div);
}
});
$("#btnNext").on('click', function(e) {
e.preventDefault();
var allValid = validateAll();
if (allValid) {
alert("No Error Found, Redirecting");
以上是关于动态创建或删除表单元素的主要内容,如果未能解决你的问题,请参考以下文章
jQuery serializeArray 没有获取动态创建的表单元素
在动态 viewpager 片段中创建 recyclerviews