php ajax based form displaying blank page - javascript

I have created a eBay Item search form. I want to make form.html to form.php but when I change it to .php the form doesn't work and display blank page. you can see form.html here:
<script>
function showDetail(name){
$("."+name).collapse('toggle');
}
function getPage(num){
var data = {
"action": "test",
"pageNumber": num
};
data = $('form').serialize() + "&" + $.param(data);
// jQuery AJAX call to PHP Script with JSON Return
$.ajax({
type: "GET",
dataType: "json",
url: "advancedItemSearchTest.php", //Relative or absolute path to response.php file
data: data,
success: function(new_data) {
$( ".container" ).hide();
$( ".the-return" ).html( "" );// clear all the contents first
if(new_data['ack'] != 'Success' || new_data['resultCount'] <= 0){
$( ".the-return" ).html( "<h2>No Results were found</h2>" );
}
else{
for ( var i = 0; i < new_data.itemCount; i++ ) {
var $media = $( '<div class = "media"></div>');
var $media_body = $( '<div class = "media-body"></div>');
var $a_class = $('<a class= "pull-left"></a>');
var $name = 'name' + i;
//<img class = "media-object" src = alt = "Item Image" />
//<?php echo $item->title ?>
var $item = new_data['item'][i];
var $imageURL = $item['basicInfo']['galleryURL'];
var $price = $item['basicInfo']['convertedCurrentPrice']
var $title = '<a href = '+ $item['basicInfo']['viewItemURL']+ '>' + $item['basicInfo']['title'] + '</a>';
var $image = '<img class = "media-object" src =' + $imageURL +'alt = "Item Image" style="width:96px;height:96px" data-toggle="modal" data-target="#myModal'+ $name +'"/>';// concatenating string must use+ for variable!!
var $modal = $('<div class="modal fade" id="myModal'+ $name +'" role="dialog"></div>');
var $modalDialog = $('<div class="modal-dialog"></div>');
var $modalContent = $('<div class="modal-content"></div>');
$modalContent.append($('<div class="modal-header"></div>').append('<h4 class="modal-title">'+$item['basicInfo']['title']+'</h4>'));
$modalContent.append($('<div class="modal-body"></div>').append('<img src='+$item['basicInfo']['pictureURLSuperSize']+' alt="Item image" style="width:512px;height:512px" align="middle">'));
$modalContent.append($('<div class="modal-footer"></div>').append('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'));
$modalDialog.append($modalContent);
$modal.append($modalDialog);
var $shippingCost = "(Free Shipping)";
if($item['basicInfo']['shippingServiceCost'] > 0){
$shippingCost = "(+$" + $item['basicInfo']['shippingServiceCost'] + ")";
}
$price = "<b>" + "Price:$" + $price + "</b>";
var $location = "<i>" + "Location:"+ $item['basicInfo']['location'] + "</i>";
var $topRated = "";
if($item['basicInfo']['topRatedListing']){
$topRated = '<img src =' + 'http://cs-server.usc.edu:45678/hw/hw8/itemTopRated.jpg' +' alt = "Top Rated" style="width:32px;height:24px" />';
}
var $collapse = $('<div class="collapse '+ $name +'"></div>');//
var $ul = $('<ul class="nav nav-tabs"></ul>');
$ul.append($('<li class="active"><a data-toggle="tab" href="#basic'+ $name +'">Basic Info</a></li>'));
$ul.append($('<li><a data-toggle="tab" href="#seller'+ $name +'">Seller Info</a></li>'));
$ul.append($('<li><a data-toggle="tab" href="#shipping'+ $name +'">Shipping Info</a></li>'));
$collapse.append($ul);
var $tabContend = $('<div class="tab-content"></div>');
var $basic = $('<div id="basic'+ $name +'" class="tab-pane fade in active"></div>');
var $table = $('<tbody></tbody>');//$('<table class = "table table-striped" ></table>');
var $tr = $('<tr></tr>');
$tr.append('<td><b>Condition</b></td>' + '<td>'+$item['basicInfo']['conditionDisplayName']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Category Name</b></td>' + '<td>'+$item['basicInfo']['categoryName']+'</td>');
$table.append($tr);
$tabContend.append($basic.append($('<table class = "table table-striped" ></table>').append($table)));
var $seller = $('<div id="seller'+ $name +'" class="tab-pane fade"></div>');
$table = $('<tbody></tbody>');//$('<table class = "table table-striped""></table>');
$tr = $('<tr></tr>');
$tr.append('<td><b>User name</b></td>' + '<td>'+$item['sellerInfo']['sellerUserName']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Feedback score</b></td>' + '<td>'+$item['sellerInfo']['feedbackScore']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Positive feedback</b></td>' + '<td>'+$item['sellerInfo']['positiveFeedbackPercent']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
var $storeName = 'N/A';
if($item['sellerInfo']['sellerStoreName']!=''){
$storeName = $item['sellerInfo']['sellerStoreName'];
}
$tr.append('<td><b>Store name</b></td>' + '<td>'+$storeName+'</td>');
$table.append($tr);
$tabContend.append($seller.append($('<table class = "table table-striped" ></table>').append($table)));
var $shipping = $('<div id="shipping'+ $name +'" class="tab-pane fade"></div>');
$table = $('<tbody></tbody>');//$('<table class = "table table-striped""></table>');
$tr = $('<tr></tr>');
$tr.append('<td><b>Shipping type</b></td>' + '<td>'+$item['shippingInfo']['shippingType']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Handling time</b></td>' + '<td>'+$item['shippingInfo']['handlingTime']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Shipping locations</b></td>' + '<td>'+$item['shippingInfo']['shipToLocations']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
//&#10004(correct) &#10008(wrong)
var $mark = "&#10008";
if($item['shippingInfo']['expeditedShipping']){
$mark = "&#10004";
}
$tr.append('<td><b>Expedited shipping</b></td>' + '<td>'+ $mark +'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
//&#10004(correct) &#10008(wrong)
var $mark = "&#10008";
if($item['shippingInfo']['returnsAccepted']){
$mark = "&#10004";
}
$tr.append('<td><b>Return accepted</b></td>' + '<td>'+ $mark +'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
//&#10004(correct) &#10008(wrong)
var $mark = "&#10008";
if($item['shippingInfo']['oneDayShippingAvailable']){
$mark = "&#10004";
}
$tr.append('<td><b>One day shipping</b></td>' + '<td>'+ $mark +'</td>');
$table.append($tr);
$tabContend.append($shipping.append($('<table class = "table table-striped" ></table>').append($table)));
$collapse.append($tabContend);
var $viewDetail= '<a onclick="showDetail(\'' + $name +'\')">View Detail</a>';//'+$name+'
$media.append($a_class.html( $image));
$media_body.append($collapse);
$media_body.prepend( '<font size="4">' + $title + '</font>' + '<br/>' + $price + $shippingCost + ' ' + $location + ' ' + $topRated + ' ' + $viewDetail );
$media.append($media_body);
$media.appendTo( $( ".the-return" ) );
$modal.appendTo( $( ".the-return" ) );
}
var $pagination = $('<div class = "pagination"></div>');
var $ul = $('<ul class="pagination"></ul>');
var $prev = num - 1;
if( num == 1){
$pagination.append($ul.append('<li class="disabled">' + '<<' + '</li>'));
}
else{
$pagination.append($ul.append('<li>' + '<<' + '</li>'));
}
for( var i = num; i < num+5; i++ ){
$pagination.append($ul.append('<li>' + i + '</li>'));
}
var $next = num + 1;
if( num == new_data['totalPages']){
$pagination.append($ul.append('<li class="disabled">' + '>>' + '</li>'));
}
else{
$pagination.append($ul.append('<li>' + '>>' + '</li>'));
}
var $itemFrom = (num-1) * Number(new_data.itemCount) + 1;
var $itemTo = $itemFrom + Number(new_data.itemCount) - 1;
var $resultNum = $( '<div class = "resultNum" ></div>').append( '<b><font size="5">'+$itemFrom +'-'+ $itemTo + ' items out of ' + new_data['resultCount'] +'</font></b>');
$resultNum.prependTo($( ".the-return" ));
$pagination.appendTo( $( ".the-return" ) );
}
},
error: function(jqXHR, textStatus, errorThrown){
//alert('error: ' + textStatus + ': ' + errorThrown);
}
});
}
$(document).ready(function(){
$('form').validate({
rules: {
keyword: { // should be name, not id!
required: true
},
priceLow: {
number: true,
digits: true
},
priceHigh: {
number: true,
digits: true
},
shippingTime:{
number: true,
digits: true
}
},
messages:{
keyword: { // should be name, not id!
required: "Please enter a keyword"
},
priceLow: {
number: "Price should be a valid number",
digits: "Price should be a valid number",
min : "Minimum price cannot be below 0"
},
priceHigh: {
number: "Price should be a valid number",
digits: "Price should be a valid number",
min : "Maximum price cannot be less than minimum price or below 0"
},
shippingTime:{
number: "Max handling time should be a valid digit",
digits: "Max handling time should be a valid digit",
min: "Max handling time should be greater than or equal to 1"
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('form').submit(function(){
//var num = 1;
getPage(1);
return false;
});
}); // end document.ready
</script>
</head>
<body>
<style>
.center_div{
margin: 0 auto;
width:80%;
}
</style>
<div class = "container center_div" >
<img src = " http://cs-server.usc.edu:45678/hw/hw8/ebay.jpg" class="img-responsive"><br>
<form class = "form-horizontal" action = "advancedItemSearchTest.php" method="GET" role = "form" id = "myForm" accept-charset="utf-8">
<div class = "form-group">
<label class="control-label col-sm-2" for="keyword">Key words:*</label>
<div class="col-sm-8">
<input type = "text" class="form-control" id = "keyword" name = "keyword" placeholder="Enter keyword">
</div>
<label class="control-label col-sm-2" for="keyword">APP ID</label>
<div class="col-sm-8">
<input type = "text" class="form-control" id = "appid" name = "appid" placeholder="Enter appID">
</div>
</div>
<div class = "form-group row">
<label class="control-label col-sm-2" for="priceLow">Price range: </label>
<div class="col-sm-4">
<input type = "number" class="form-control" name = "priceLow" id = "priceLow" min="0" placeholder="from($)">
</div>
<label class="control-label " for="priceHigh"> </label>
<div class="col-sm-4">
<input type = "number" class="form-control" name = "priceHigh" id = "priceHigh" min="0" placeholder="to($)">
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="conditionNew">Condition: </label>
<div class="col-sm-8">
<label class="checkbox-inline"><input type="checkbox" id = "conditionNew" name = "condition[]" value=1000>New</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=3000>Used</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=4000>Very Good</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=3000>Good</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=4000>Acceptable</label>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="formats">Buying formats: </label>
<div class="col-sm-8">
<label class="checkbox-inline"><input type="checkbox" id = "formats" name = "BuyFormat[]" value="FixedPrice">Buy It Now</label>
<label class="checkbox-inline"><input type="checkbox" name = "BuyFormat[]" value="Auction">Auction</label>
<label class="checkbox-inline"><input type="checkbox" name = "BuyFormat[]" value="Classified">Classified Ad</label>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="shipping">Shipping: </label>
<div class="col-sm-8">
<label class="checkbox-inline"><input type="checkbox" id = "shipping" name = "FreeShippingOnly" value="true">Free Shipping</label>
<label class="checkbox-inline"><input type="checkbox" name = "ExpeditedShippingType" value="Expedited">Expedited shipping</label>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="shippingTime"> </label>
<div class="col-sm-8">
<input type = "number" class="form-control" name = "shippingTime" id = "shippingTime" min="1" placeholder="Max handling time(days)">
</div>
</div>
</div>
</div>
<div class="form-group col-sm-10" align="right">
<input type="reset" class="btn btn-default" value="Clear" >
<input type="submit" class="btn btn-primary" value="Search">
</div>
</form>
when form is in .html extension it works fine but when I change it to .php it display blank page.

Change the last button type from submit to button.
In submit It will redirect on new page.

Related

Dynamically create or remove form elements

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>

Total of all input fields not coming as correct answer

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'm relatively new to Javascript. I'm creating a CRUD based application and I need help in the Edit function

I am trying to create a pure Javascript CRUD application. The data is displayed in an HTML Table.
I have created the Create, Read and delete function. In the Edit function, I want the data to be displayed on a text box when the edit link is clicked and should also have a save button.
How should I proceed ?
var name = document.getElementById('Name').value;
var age = document.getElementById('Age').value;
var email = document.getElementById('Email').value;
var password = document.getElementById('Password').value;
var confirmpassword = document.getElementById('ConfirmPassword').value;
var dob = document.getElementById('DOB').value;
//add
var users = [];
function data(name, age, email, dob) {
var user = {
"name": name,
"age": age,
"email": email,
"dob": dob
}
users.push(user);
read(users);
console.log(users);
}
//Read
function read(users) {
var html = "<table border='1|1'>";
html += "<tr>";
html += "<th>" + "Name" + "</th>"
html += "<th>" + "Age" + "</th>"
html += "<th>" + "Email" + "</th>";
html += "<th>" + "DOB" + "</th>";
html += "<th>" + "Edit" + "</th>";
html += "<th>" + "Delete" + "</th>";
html += "</tr>"
var userhtml = document.getElementById('user');
userhtml.innerHTML = '';
for (var i = 0; i < users.length; i++) {
html += "<tr>";
html += "<td>" + users[i].name + "</td>";
html += "<td>" + users[i].age + "</td>";
html += "<td>" + users[i].email + "</td>";
html += "<td>" + users[i].dob + "</td>";
html += "<td>" + "<a href='#' onclick='editUsers()'>Edit</a>" + "</td>";
html += "<td>" + "<a href='#' onclick='deleteUsers()'>Delete</a>" + "</td>";
html += "</tr>";
}
html += "</table>";
document.getElementById("user").innerHTML = html;
}
function deleteUsers(i) {
debugger;
users.splice(i, 1)
read();
console.log(users);
}
<form action="#" onsubmit="data(name, age, email, dob)">
<div class="form-group">
<label class="form-text">Name :</label>
<input type="text" id="Name" placeholder="Enter Name" class="form-control" />
<span id="ErrorName" class="text-danger"></span>
</div>
<div class="form-group">
<label class="form-text">Age :</label>
<input type="text" id="Age" placeholder="Enter Age" class="form-control" />
<span id="ErrorAge" class="text-danger"></span>
</div>
<div class="form-group">
<label class="form-text">Email :</label>
<input type="text" id="Email" placeholder="Enter Email" class="form-control" />
<span id="ErrorEmail" class="text-danger" />
</div>
<div class="form-group">
<label class="form-text">Password :</label>
<input type="password" id="Password" placeholder="Enter Password" class="form-control" />
<span id="ErrorPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label class="form-text">Confirm Password :</label>
<input type="password" id="ConfirmPassword" placeholder="Confirm Password" />
<span id="ErrorConfirmPassword" class="text-danger"></span>
</div>
<div class="form-group">
<label class="form-text">Date of Birth :</label>
<input type="date" id="DOB" class="form-control" />
<span id="ErrorDOB" class="text-danger"></span>
</div>
<div class="form-group col-xl-4 text-center">
<input type="submit" id="Submit" class="btn btn-success" />
</div>
</form>
<div class="user" id="user">
</div>
function editUsers(index) {
var x = document.getElementById('edit');
x.style.display = "block";
debugger;
var userhtml1 = document.getElementById('edit');
userhtml1.innerHTML = '';
for (var i = 0; i < users.length; i++) {
if (i == index) {
userhtml1.innerHTML += ' <div class="form-group"> Name :<input class="form-control" id="EditName" type="text" value ="' + users[i].name + '"><br />' +
'Age :<input class="form-control" id="EditAge" type="text" value="' + users[i].age + '"> <br /> ' +
'Email :<input class="form-control" id="EditEmail" type="text" value="' + users[i].email + '"> <br /> ' +
'DOB :<input class="form-control" id="EditDOB" type="text" value="' + users[i].dob + '"> <br /> ' +
'<button class="edit" onclick="updateUser(' + i + ')">Update</button>';
}
else {
userhtml1.innerHTML += '';
}
}
}
//CRUD - UPDATE
function updateUser(index) {
debugger;
var updatename = document.getElementById('EditName').value;
var updateage = document.getElementById('EditAge').value;
var updateemail = document.getElementById('EditEmail').value;
var updatedob = document.getElementById('EditDOB').value;
if (updatename == '' || updateemail == '' || updateage == '' || updatedob == '') {
alert("Please Fill the Fields!");
}
else {
users[index].name = updatename;
users[index].email = updateemail;
users[index].age = updateage;
users[index].dob = updatedob;
read(users);
var x = document.getElementById('edit');
x.style.display = "none";
}
}

Concatenate select box selected values

Thanks in advance! I am building an application using asp.net web form that have one dropdownlist and two listbox, which needs to be clone whenever a button is click. My problem is I'm currently hard coding a lot of code and I will like to make it more dynamic. Can everyone help me figure this out?
Here is an example of what my current script is doing.
Code:
$(document).ready(function() {
var clone = (function() {
var cloneIndex = 0;
var template = $('#categoryTemplate').text();
return function() {
return template.replace(/ID/g, ++cloneIndex);
}
})();
//Start off with 1 category.
categories.append(clone());
var sbClone1 = new StringBuilder();
$(document).on('change', '#MainContent_ddlWarehouse1', function () {
var myele = '';
sbClone1.strings[0] = [];
var mystring = '';
myele = $(this).val();
sbClone1.strings[0] = 'SELECT top 10 ' + myele + ', PART_CODE, WAREHOUSE, UNIT_OF_MEASURE, MOVEMENT_DATE, MOVEMENT_CODE, [IC_MOVE_QUANTITY] FROM [dbo].[IC_MOVEMENTS] WHERE MOVEMENT_DATE between "' + startDateTextBox.val() + '" and "' + endDateTextBox.val() + '" AND WAREHOUSE = "' + myele + '" ';
mystring = sbClone1.toString();
$('#MainContent_hfConcatString').val(mystring);
document.getElementById("MainContent_Label1").innerHTML = mystring;
});
$(document).on('change', '#MainContent_lbMovementCode1', function () {
var myele = '';
sbClone1.strings[1] = [];
var mystring = '';
myele = $(this).val();
sbClone1.strings[1] = 'AND MOVEMENT_CODE IN "' + myele + '" ';
mystring = sbClone1.toString();
$('#MainContent_hfConcatString').val(mystring);
document.getElementById("MainContent_Label1").innerHTML = mystring;
});
$(document).on('change', '#MainContent_lbUnitofMeasure1', function () {
var myele = '';
sbClone1.strings[2] = [];
var mystring = '';
myele = $(this).val();
sbClone1.strings[2] = ' AND UNIT_OF_MEASURE IN "' + myele + '" ';
mystring = sbClone1.toString();
$('#MainContent_hfConcatString').val(mystring);
document.getElementById("MainContent_Label1").innerHTML = mystring;
});
$(document).on("click", 'button.add', function() {
categories.append(clone());
});
});
<script type="text/template" id="categoryTemplate">
<div class="category" id="DatasetID">
<div class="row">
<!-- Warehouse Category -->
<div class="col col-lg-4">
<div class="form-group">
<label class="control-label" for="WarehouseID">Warehouse</label>
<asp:DropDownList ID="ddlWarehouseID" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="Please Select"></asp:ListItem>
</asp:DropDownList>
</div>
</div>
<!-- MovementCode Category -->
<div class="col col-lg-4">
<div class="form-group">
<label class="control-label" for="MovementCodeID">Movement Code</label>
<asp:ListBox ID="lbMovementCodeID" runat="server" SelectionMode="Multiple">
</asp:ListBox>
</div>
</div>
<!-- UnitofMeasure Category -->
<div class="col col-lg-4">
<div class="form-group">
<label class="control-label" for="UnitofMeasureID">Unit of Measure</label>
<asp:ListBox ID="lbUnitofMeasureID" runat="server" SelectionMode="Multiple">
</asp:ListBox>
</div>
</div>
</div>
</div>
</script>
There is no need to iterate through the options, try following:
var string = $("[name=cars]").val().join(", ")

Javascript, Jquery - Adding url images

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.

Categories

Resources