I'm creating a Dynamic Form Elements in which I have to add multiple dependents.
My code is below.
In my project, I have to add at least one dependent which I have created using HTML, but user is allowed to add as much as the user wants, therefore I am using jQuery for this and creating the same form dynamically, on user button click, and also user have the choice to remove it.
I have applied some validation too, before adding up a new dependent, the user must fill out all the fields on a click of Add Dependant button. Further, on Add Dependant button I'm just validating the previous form using counter.
I'm using a Counter variable and checking the last added form using it, and incrementing it when user have created a form, and on remove I'm just decrementing it.
On Next button, I'm validating the whole form controls, because user may have deleted or left any field empty, therefore I'm checking this on the click of next button.
The problem is when add up 2 or more than 2 forms and then I remove the middle one or the 2nd one, Add Dependant and Next button stop doing anything, which is causing me problem. I want this form like user may add and delete anytime.
How can I achieve that?
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>
View on jsFiddle
I think you have a problem with your counter variable.
When you remove a form in the middle, you decrement your counter ... but the previous form is still the same as before the removing.
Instead of using a counter, why don't you use previous and next function of Jquery?
As others have mentioned, decrementing counter throws off ID references when validating.
I suggest using classes rather than IDs. Then you can iterate through each .form-row and validate inputs within each block by using selector context or find(). Like this:
$('.errorFirstName', this)
Here's a demonstration:
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");
}
});
$("body").on("click", ".removeitem", function(e) {
e.preventDefault();
counter--;
$(this).closest('.my-3').remove();
});
// add initial form block
var div = GetDynamicTextBox();
$("#TextBoxContainer").append(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>
</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>
</div>
I've associated labels and inputs implicitly, by nesting inputs inside of their labels. That allowed me to get rid of counter altogether. If you prefer, you can associate them explicitly using incremented IDs (for=""). The idea is just not to use those IDs for validation iteration.
Edit
Above, I'm generating the initial form block from JavaScript, using the same function the "Add Button" uses. If you like, you can include the initial form block in your HTML, like you originally had it.
Like 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");
}
});
$("body").on("click", ".removeitem", function(e) {
e.preventDefault();
counter--;
$(this).closest('.my-3').remove();
});
<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="my-3 border border-dark rounded 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 class="font-weight-bold small">First Name<input type="text" name="DependentFName" placeholder="First Name" class="form-control inputFirstName"></label><span class="form-text text-danger small errorFirstName"></span></div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Middle Name<input type="text" name="DependentMName" placeholder="Middle Name" class="form-control inputMiddleName"></label><span class="form-text text-danger small errorMiddleName"></span></div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Last Name<input type="text" name="DependentLName" placeholder="Last Name" class="form-control inputLastName"></label><span class="form-text text-danger small errorLastName"></span></div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Date of Birth <span class="small">(MM/DD/YYYY)</span><input type="text" name="DependentDateOfBirth" placeholder="MM/DD/YYYY" class="form-control inputDOB"></label><span class="form-text text-danger small errorDOB"></span></div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Gender<select name="DepGender" class="form-control inputGender"><option value="-1" selected="selected">Select Gender</option><option value="M">Male</option><option value="F">Female</option></select></label>
<span class="form-text text-danger small errorGender"></span>
</div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Relationship to Primary Applicant<select name="DependantRelationship" class="form-control inputRelationship"><option value="-1" selected="selected">Select Relationship</option><option value="SP">Spouse or Domestic Partner</option><option value="CH">Child</option></select></label>
<span class="form-text text-danger small errorRelationship"></span>
</div>
</div>
</div>
</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>
</div>
You are having a problem in counter variable and id of your fields.
Basically you are trying to get a form that does not exist.
This happens when you are adding 2 extra forms witch result in input elements with id 1,2 and 3 but when you delete the middle one witch is 2 the counter is still at 3. So when you want to validate you inputs input 2 does not exist. Witch stop the JavaScript execution.
I fixed it by adding if elements in both loops in the next element button click event. witch they check if the element exist and then try to access it.
As you mentioned. Also delete counter-- when you are removing the form
var counter = 0;
var regexDoB = new RegExp('([0-9][1-2])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2})');
var getLastValidId = function(){
var lastId = $('#TextBoxContainer').children().last().find("input").first().attr("id").match(/\d+/);
return lastId;
}
$("#btAdd").on('click', function(e) {
e.preventDefault();
var counter1 = getLastValidId()
$('#errorDepFirstName' + counter1).html("");
$('#errorDepLastName' + counter1).html("");
$('#errorDepDateOfBirth' + counter1).html("");
$('#errorDepGender' + counter1).html("");
$('#errorDepRelationship' + counter1).html("");
if ($('#txtDepFirstName' + counter1).val() == '') {
$('#errorDepFirstName' + counter1).html("Please provide Dependent's First Name");
$('#txtDepFirstName' + counter1).focus();
return false;
} else if ($('#txtDepLastName' + counter1).val() == '') {
$('#errorDepLastName' + counter1).html("Please provide Dependent's Last Name");
$('#txtDepLastName' + counter1).focus();
return false;
} else if ($('#txtDepDateOfBirth' + counter1).val() == '') {
$('#errorDepDateOfBirth' + counter1).html("Please provide Dependent's Date of Birth");
$('#txtDepDateOfBirth' + counter1).focus();
return false;
} else if (!regexDoB.test($('#txtDepDateOfBirth' + counter1).val())) {
$('#errorDepDateOfBirth' + counter1).html("Invalid Dependent's Date of Birth");
$('#txtDepDateOfBirth' + counter1).focus();
return false;
} else if ($('#ddDepGender' + counter1).val() == -1) {
$('#errorDepGender' + counter1).html("Please select Dependent's Gender");
$('#ddDepGender' + counter1).focus();
return false;
} else if ($('#ddDepRelationship' + counter1).val() == -1) {
$('#errorDepRelationship' + counter1).html("Please select relation with Dependent");
$('#ddDepRelationship' + counter1).focus();
return false;
} else if ($('#ddDepRelationship' + counter1).val() == 'CH' && getAge($('#txtDepDateOfBirth' + counter1).val()) > 25) {
$('#errorDepDateOfBirth' + counter1).html("Child Dependent's must be age 25 or younger");
$('#txtDepDateOfBirth' + counter1).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++) {
if($('#errorDepFirstName' + j).length > 0){
$('#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($('#errorDepFirstName' + i).length > 0){
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();
$(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>
<button onclick="getLastValidId()">A</button>
var checkSum = 0;
var jsonData = {};
var pushData;
var trData = [];
var sumData = [];
var chkArray = [];
countTab2 = 1;
$(".add-customs").click(function() {
customsTable();
});
function customsTable() {
var markup = "<div class='col-md-1'>Custom</div>" +
"<div class='col-md-4'><input id='customReason" +
countTab2 +
"' type='text' value='' class='txt form-control'" +
"name='customReason' path='customReason' /></div>" +
"<div class='col-md-2'><input value='0' type='text' class='txt form-control'" +
"name='customAmount' id='customAmount" +
countTab2 +
"'></div>" +
"<div class='col-md-2'><input value='0' onchange='getCustomTotal();' type='text' class='txt form-control'" +
"name='customPenalty' id='customPenalty" +
countTab2 +
"'></div>" +
"<div class='col-md-1'><span id='customSum" +
countTab2 +
"'>0</span></div>" +
"<div class='col-md-2'></div>";
countTab2++;
$(".custom-table").append(markup);
}
//adding row for VAT
countTab3 = 1;
$(".add-vat").click(function() {
vatTable();
});
function vatTable() {
var markup = "<div class='col-md-1'>VAT</div>" +
"<div class='col-md-4'><input id='vatReason" +
countTab3 +
"' type='text' value='' class='txt1 form-control'" +
"name='vatReason' /></div>" +
"<div class='col-md-2'><input type='text' class='txt1 form-control'" +
"name='vatAmount' value='0' id='vatAmount" +
countTab3 +
"'></div>" +
"<div class='col-md-2'><input type='text' value='0' onchange='getVatTotal();' class='txt1 form-control'" +
"name='vatPenalty' id='vatPenalty" +
countTab3 +
"'></div>" +
"<div class='col-md-1'><span id='vatTotal" +
countTab3 +
"'></span></div>" +
"<div class='col-md-2'></div>";
countTab3++;
$(".vat-table").append(markup);
}
//adding row for Excise
countTab4 = 1;
$(".add-excise").click(function() {
exciseTable();
});
function exciseTable() {
var markup = "<div class='col-md-1'>Excise</div>" +
"<div class='col-md-4'><input id='exciseReason" +
countTab4 +
"' type='text' value='' class='txt2 form-control'" +
"name='exciseReason' /></div>" +
"<div class='col-md-2'><input type='text' class='txt2 form-control'" +
"name='exciseAmount' value='0' id='exciseAmount" +
countTab4 +
"'></div>" +
"<div class='col-md-2'><input type='text' onchange='getExciseTotal();' class='txt2 form-control'" +
"name='excisePenalty' value='0' id='excisePenalty" +
countTab4 +
"'></div>" +
"<div class='col-md-1'><span id='exciseTotal" +
countTab4 +
"'></span></div>" +
"<div class='col-md-2'></div>";
countTab4++;
$(".excise-table").append(markup);
}
customs = [];
function getListCustoms() {
for (i = 0; i < countTab2; i++) {
if ($("#customPenalty" + i).length) {
customs.push({
assessReason: $("#customReason" + i).val(),
assessAmount: $("#customAmount" + i).val(),
assessPenalty: $("#customPenalty" + i).val()
});
}
}
}
function getCustomTotal() {
var customTotal = 0;
getListCustoms();
customs.unshift({
assessReason: $("#customReason").val(),
assessAmount: $("#customAmount").val(),
assessPenalty: $("#customPenalty").val()
});
customTotal = customTotal + parseInt(customs[0].assessAmount) +
parseInt(customs[0].assessPenalty);
for (i = 1; i < customs.length; i++) {
customTotal = customTotal + parseInt(customs[i].assessAmount) +
parseInt(customs[i].assessPenalty);
customRowTotal = 0;
customRowTotal = parseInt($("#customAmount" + i).val()) +
parseInt($("#customPenalty" + i).val());
$("#customSum" + i).html(customRowTotal);
}
getTotalSum();
$('#tot').html(wholeTotal);
}
$("#customPenalty").change(
function() {
totalCustom = 0;
totalCustom = parseInt($("#customAmount").val()) +
parseInt($("#customPenalty").val());
$("#customSum").html(totalCustom);
});
function getVatTotal() {
var vatTotal = 0;
getVatList();
vats.unshift({
assessReason: $("#vatReason").val(),
assessAmount: $("#vatAmount").val(),
assessPenalty: $("#vatPenalty").val()
});
vatTotal = vatTotal + parseInt(vats[0].assessAmount) +
parseInt(vats[0].assessPenalty);
for (i = 1; i < vats.length; i++) {
vatTotal = vatTotal + parseInt(vats[i].assessAmount) +
parseInt(vats[i].assessPenalty);
vatRowTotal = 0;
vatRowTotal = parseInt($("#vatAmount" + i).val()) +
parseInt($("#vatPenalty" + i).val());
$("#vatTotal" + i).html(vatRowTotal);
}
getTotalSum();
$('#tot').html(wholeTotal);
}
$("#vatPenalty").change(
function() {
totalVat = 0;
totalVat = parseInt($("#vatAmount").val()) +
parseInt($("#vatPenalty").val());
$("#vatTotal").html(totalVat);
});
vats = [];
function getVatList() {
for (i = 0; i < countTab3; i++) {
if ($("#vatPenalty" + i).length) {
vats.push({
assessReason: $("#vatReason" + i).val(),
assessAmount: $("#vatAmount" + i).val(),
assessPenalty: $("#vatPenalty" + i).val()
});
}
}
}
excises = [];
function getExciseList() {
for (i = 0; i < countTab4; i++) {
if ($("#excisePenalty" + i).length) {
excises.push({
assessReason: $("#exciseReason" + i).val(),
assessAmount: $("#exciseAmount" + i).val(),
assessPenalty: $("#excisePenalty" + i).val()
});
}
}
}
$("#excisePenalty").change(
function() {
totalExcise = 0;
totalExcise = parseInt($("#exciseAmount").val()) +
parseInt($("#excisePenalty").val());
/* $("#tot").html(totalVat+totalCustom); */
$("#exciseTotal").html(totalExcise);
});
function getExciseTotal() {
var exciseTotal = 0;
getExciseList();
excises.unshift({
assessReason: $("#exciseReason").val(),
assessAmount: $("#exciseAmount").val(),
assessPenalty: $("#excisePenalty").val()
});
exciseTotal = exciseTotal + parseInt(excises[0].assessAmount) +
parseInt(excises[0].assessPenalty);
for (i = 1; i < excises.length; i++) {
exciseTotal = exciseTotal + parseInt(excises[i].assessAmount) +
parseInt(excises[i].assessPenalty);
exciseRowTotal = 0;
exciseRowTotal = parseInt($("#exciseAmount" + i).val()) +
parseInt($("#excisePenalty" + i).val());
$("#exciseTotal" + i).html(exciseRowTotal);
}
getTotalSum();
$('#tot').html(wholeTotal);
}
function getTotalSum() {
wholeTotal = 0;
var allList = customs.concat(vats, excises);
for (i = 0; i < allList.length; i++) {
wholeTotal += parseInt(allList[i].assessAmount) + parseInt(allList[i].assessPenalty);
}
console.log(wholeTotal);
}
//submit method now
$("form").submit(function() {
event.preventDefault();
getTotalSum();
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<form>
<div class="col-md-12" style="float: none;">
<!-- <button onclick="myFunction()" class="pull-right">+</button> -->
<div style="margin-bottom: 30px;">
<div class="form-group row">
<div class="col-md-1"></div>
<div class="col-md-4">
<label>Reason</label>
</div>
<div class="col-md-2">
<label>Amount</label>
</div>
<div class="col-md-2">
<label>Penalty</label>
</div>
<div class="col-md-1">Total</div>
<div class="col-md-2">Action</div>
</div>
<div class="custom-table row">
<div class="col-md-1">
<label>Customs</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="customReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt" id="customAmount" value="0" name="abc" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt" id="customPenalty" onchange="getCustomTotal();" value="0" name="abc" min="0" />
</div>
<div class="col-md-1">
<span id="customSum">0</span>
</div>
<div class="col-md-2">
<button class="add-customs">+</button>
</div>
</div>
<div class="vat-table row">
<div class="col-md-1">
<label>VAT</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="vatReason" name="vatReason" />
</div>
<div class="col-md-2">
<input type="text" class="form-control txt1" id="vatAmount" value="0" name="vatAmount" min="0" />
</div>
<div class="col-md-2">
<input type="text" class="form-control txt1" id="vatPenalty" value="0" name="vatPenalty" onchange="getVatTotal();" min="0" />
</div>
<div class="col-md-1">
<span id="vatTotal">0</span>
</div>
<div class="col-md-2">
<button class="add-vat">+</button>
</div>
</div>
<div class="excise-table row">
<div class="col-md-1">
<label>Excise</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control" id="exciseReason" name="exciseReason" />
</div>
<div class="col-md-2">
<input type="text" class="form-control txt2" id="exciseAmount" value="0" name="exciseAmount" min="0" />
</div>
<div class="col-md-2">
<input type="text" class="form-control txt2" id="excisePenalty" value="0" name="excisePenalty" onchange="getExciseTotal();" min="0" />
</div>
<div class="col-md-1">
<span id="exciseTotal">0</span>
</div>
<div class="col-md-2">
<button class="add-excise">+</button>
</div>
<div class="col-md-1 pull-right">
<label>Total:</label> <b> <span id="tot">0</span></b>
</div>
</div>
</div>
<button type="submit" class="btn btn-success pull-right">Submit</button>
</div>
</form>
I have the form looking like this:
The total of the respective row is shown successfully but the total of all the input field is not showing as expected. And when I clear one input field then its data is not subtracted from the total. I am not able to get the correct sum of all the input fields which are dynamic. How can I make the changes here?
UPDATE:
when I am typing some data in "amount" and "penalty" then the total is also coming just after Penalty "column".
Can I pass those individual Total to the array like
{
assessmentType: "PRE",
assessCatID: 1,
assessReason: "11",
assessAmount: "22",
assessPenalty: "33"
}
I need a new field customOneRowTotal:22+33 and need to be inserted in array
Updated code(December 9,2018):
I have a AJAX calling a API and it has successfully arrived in my console:
var table = $('#nepal')
.DataTable(
{
"processing" : true,
"ajax" : {
"url" : A_PAGE_CONTEXT_PATH
+ "/form/api/getSelectionByAssessmentOrNonAssessment",
dataSrc : ''
},
"columns" : [ {
"data" : "selectionId"
}, {
"data" : "selectionDate"
}, {
"data" : "selectedBy"
}, {
"data" : "eximPanNo"
}, {
"data" : "eximPanName"
}, {
"data" : "eximPanAddr"
}, {
"data" : "eximPanPhone"
}, {
"data" : "selectionType"
}, {
"data" : "auditorGroupName"
} ]
});
Data is shown recently on Datatable and when I click on the single row then it is selected and populated as:
The JSON Data coming through this Ajax Call is:(We need assessCatAmount data recently now from this whole JSON data)
{
"selectionId":1,
"selectionDate":"2075-08-15",
"selectedBy":"Department",
"eximPanNo":1234,
"eximPanName":"PCS",
"eximPanNameEng":"PCS",
"eximPanAddr":"KAPAN",
"eximPanAddrEng":"PCS",
"eximPanPhone":9843709166,
"selectionType":"consignment\r\n",
"consignmentNo":122,
"consignmentDate":"2018-2-6",
"productName":null,
"selectionFromDate":"2018-11-30",
"selectionToDate":"2018-11-28",
"agentNo":3,
"selectionStatus":"1",
"entryBy":"1",
"entryDate":"2018-11-25 11:25:11",
"rStatus":"1",
"custOfficeId":1,
"selectionAudit":null,
"letter":null,
"auditorGroupName":null,
"document":null,
"assessment":{
"assessmentNo":1,
"assessmentType":"PRE",
"offCode":null,
"assessmentDate":"2071",
"assessmentBy":null,
"totalAssessment":null,
"selectionId":1,
"assSec":null,
"assRule":null,
"parentAssessmentId":null,
"appealId":445,
"demandNo":null,
"eximCd":null,
"consignmentNo":null,
"assessFrom":null,
"assessTo":null,
"assessReason":null,
"reasonDesc":null,
"intCalUpto":"2070",
"assessBasis":null,
"entryBy":"PCS",
"rStatus":"1"
},
"assessCatAmount":[
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":1,
"assessReason":"A",
"assessAmount":1,
"assessPenalty":2,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":1,
"assessReason":"D",
"assessAmount":3,
"assessPenalty":4,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":2,
"assessReason":"B",
"assessAmount":5,
"assessPenalty":6,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":2,
"assessReason":"E",
"assessAmount":7,
"assessPenalty":8,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":3,
"assessReason":"C",
"assessAmount":9,
"assessPenalty":10,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":3,
"assessReason":"F",
"assessAmount":10,
"assessPenalty":10,
"entryBy":"PCS",
"rStatus":"1"
}
]
}
Now we have this form as:
Now i need to populate those six assessCatAmount data into this table. how can i get this?
When i click on Datatable the action of clicking is happening by:
.selected {
background-color: #a7d8d3;
}
$('#nepal tbody').on('click', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
trDataSecondTable = table.row(this).data();
console.log(trDataSecondTable);
});
everything is stored in trDataSecondTable on click of row of the datatable.
$('#chooseButton')
.on(
'click',
function() {
$('.hidden')
.css('display', 'block');
$("#panEximName")
.html(
trDataSecondTable.eximPanNameEng);
$("#panEximPhone")
.html(
trDataSecondTable.eximPanPhone);
for (var i = 0; i < trDataSecondTable.document.length; i++) {
if ($("#invoice").val() == trDataSecondTable.document[i].docNameEng) {
$("#invoice").prop(
'checked', true);
} else if ($("#packingList")
.val() == trDataSecondTable.document[i].docNameEng) {
$("#packingList").prop(
'checked', true);
} else {
$("#invoice").prop(
'checked', false);
$("#packingList").prop(
'checked', false);
}
}
$("#inoutDate")
.val(
trDataSecondTable.letter[0].inoutDate);
});
You need to delegate and not use inline event handling
Delegate and clone - I changed the div class to match customs instead of custom
Sum on every change
Change all buttons to type="button" to not submit on [+]
I moved the grand total out of the excise row
function sumIt() {
$("#formContainer [type=number]").each(function() {
var $row = $(this).closest(".row");
var $fields = $row.find("[type=number]");
var val1 = $fields.eq(0).val();
var val2 = $fields.eq(1).val();
var tot = (isNaN(val1) ? 0 : +val1) + (isNaN(val2) ? 0 : +val2)
$row.find(".sum").text(tot);
});
var total = 0;
$(".sum").each(function() {
total += isNaN($(this).text()) ? 0 : +$(this).text()
});
$("#tot").text(total);
return total;
}
$(".customs-table .remove:lt(1)").hide();
$(".vat-table .remove:lt(1)").hide();
$(".excise-table .remove:lt(1)").hide();
$("#formContainer").on("click", "button", function() {
var selector = "div.row";
var $div = $(this).closest(selector);
if ($(this).is(".add")) {
var $newDiv = $div.clone();
$newDiv.find(":input").val(""); // clear all
$newDiv.find("[type=number]").val(0); // clear numbers
$newDiv.find(".sum").text(0); // clear total
$newDiv.insertAfter($div)
}
else {
$div.remove();
sumIt();
}
$(".customs-table .remove:gt(0)").show();
$(".vat-table .remove:gt(0)").show();
$(".excise-table .remove:gt(0)").show();
});
$("#formContainer").on("input", "[type=number]", sumIt);
$("form").submit(function() {
event.preventDefault();
var user_profile = [];
$(".row").each(function() {
var $fields = $(this).find(":input");
if ($fields.length > 0) {
var cat = $(this).find("div>label").eq(0).text(); // use the label of the row
var catId = ["","Customs","VAT","Excise"].indexOf(cat)
user_profile.push({
assessmentType: "PRE",
assessCatID : catId,
assessReason: $fields.eq(0).val(),
assessAmount: $fields.eq(1).val(),
assessPenalty: $fields.eq(2).val(),
assessTotal: +$fields.eq(1).val() + +$fields.eq(2).val() // the leading + makes it a number
});
}
});
console.log(user_profile);
/*
$.ajax({
url: "someserverfunction",
data: JSON.encode(user_profile),
success : function(data) { }
error: function() { }
});
*/
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<form id="myForm">
<div id="formContainer" class="col-md-12" style="float: none;">
<!-- <button onclick="myFunction()" class="pull-right">+</button> -->
<div style="margin-bottom: 30px;">
<div class="form-group row">
<div class="col-md-1"></div>
<div class="col-md-4">
<label>Reason</label>
</div>
<div class="col-md-2">
<label>Amount</label>
</div>
<div class="col-md-2">
<label>Penalty</label>
</div>
<div class="col-md-1">Total</div>
<div class="col-md-2">Action</div>
</div>
<div class="customs-table row">
<div class="col-md-1">
<label>Customs</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control customReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt customAmount" value="0" name="abc" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt customPenalty" value="0" name="abc" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="vat-table row">
<div class="col-md-1">
<label>VAT</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control vatReason" name="vatReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt1 vatAmount" value="0" name="vatAmount" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt1 vatPenalty" value="0" name="vatPenalty" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="excise-table row">
<div class="col-md-1">
<label>Excise</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control exciseReason" name="exciseReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt2 exciseAmount" value="0" name="exciseAmount" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt2 excisePenalty" value="0" name="excisePenalty" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="col-md-12 pull-right">
<label>Total:</label> <b><span id="tot">0</span></b>
</div>
</div>
<button type="submit" class="btn btn-success pull-right">Submit</button>
</div>
</form>
i am trying to get an image from a given url. but i am unsure where i am going wrong in my coding. The url link is displayed but not the image of the url
for example, i would like to paste this url link
https://www.petfinder.com/wp-content/uploads/2012/11/dog-how-to-select-your-new-best-friend-thinkstock99062463.jpg
for my coding to display the image and not the link
Any help would be much appreciated
$(function() {
var dialog, form,
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
url = $("#url"),
// url = $('#elementId').attr('src');
name = $("#name"),
email = $("#email"),
company = $("#company"),
password = $("#password"),
allFields = $([]).add(url).add(name).add(email).add(company).add(password),
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function() {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function checkRegexp(o, regexp, n) {
if (!(regexp.test(o.val()))) {
o.addClass("ui-state-error");
updateTips(n);
return false;
} else {
return true;
}
}
function addUser() {
var valid = true;
allFields.removeClass("ui-state-error");
valid = valid && checkLength(name, "username", 3, 16);
valid = valid && checkLength(email, "email", 6, 80);
valid = valid && checkLength(name, "company", 3, 16);
valid = valid && checkLength(password, "password", 5, 16);
valid = valid && checkRegexp(name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter.");
valid = valid && checkRegexp(email, emailRegex, "eg. ui#jquery.com");
valid = valid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");
if (valid) {
$("#users tbody").append("<tr>" +
"<td>" + url.val() + "</td>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + company.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>");
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 510,
width: 400,
modal: true,
buttons: {
// addClass: "account-btn",
"GET STARTED": addUser,
// Cancel: function() {
// dialog.dialog( "close" );
// }
},
close: function() {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function(event) {
event.preventDefault();
addUser();
});
$("#create-user").button().on("click", function() {
dialog.dialog("open");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- modal/dialog form -->
<div id="dialog-form" title="">
<form>
<fieldset>
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" value="username" class="text ui-widget-content ui-corner-all">
<label for="email">Your Email:</label>
<input type="text" name="email" id="email" value="username#example.com" class="text ui-widget-content ui-corner-all">
<label for="company">Your Company Name:</label>
<input type="text" name="company" id="company" value="example ltd" class="text ui-widget-content ui-corner-all">
<label for="password">Your Password:</label>
<input type="password" name="password" id="password" value="xxxxxxx" class="text ui-widget-content ui-corner-all">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
<label for="url">Image Url</label>
<input type="text" name="url" id="url" value="http://example.com/picture.jpg" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
<!-- table -->
<div class="L-1-1" id="users-contain" class="ui-widget">
<h1 class="table_title">Existing Users</h1>
<table id="users" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th class="first">Image</th>
<th>Name</th>
<th>Email</th>
<th>Company Name</th>
<th class="last">Password</th>
</tr>
</thead>
<tbody>
<tr>
<td>image</td>
<td>Richill Tamakloe</td>
<td>richill.tamakloe#example.com</td>
<td>Example Ltd</td>
<td>coder1</td>
</tr>
</tbody>
</table>
</div>
<button id="create-user">CREATE NEW USER</button>
You should replace this line:
"<td>" + url.val() + "</td>" +
with something like this:
"<td><img src='" + url.val() + "' /></td>" +
so that the actual image is shown in the table cell.