form with dynamic time intervals and depending disabledTimeIntervals-settings - javascript

Using eonasdan/bootstrapdatetimepicker, I try to solve this:
How to set disabledTimeIntervals, minDate and maxDate for each dynamically created time-input-field? minDate and maxDate has to be set to the corresponding field, while disabledTimeIntervals has to be set to all fields, except the edited fields - also on every edit.
I do not have any glue to get this done.
Has anyone a solution for this?
$(document).ready(function() {
$("#timeday0from").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
$("#timeday0until").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
$("#timeday0from").on("dp.change", function(e) {
$("#timeday0until")
.data("DateTimePicker")
.minDate(e.date);
});
$("#timeday0until").on("dp.change", function(e) {
$("#timeday0from")
.data("DateTimePicker")
.maxDate(e.date);
});
});
var i = 0;
var day = "day_";
var original = document.getElementById(day + i);
function duplicateElement() {
var clone = original.cloneNode(true);
i++;
clone.id = day + i; // there can only be one element with an ID
clone.childNodes;
for (var input of $(".timeday0from", clone)) {
input.id = "time" + clone.id + "from";
}
for (var input of $(".timeday0until", clone)) {
input.id = "time" + clone.id + "until";
}
for (var select of $(".timeday0type", clone)) {
select.id = "time" + clone.id + "info";
}
for (var input of $(".timeday0from", clone)) {
input.name = "time[" + day + "][" + i + "][from]";
}
for (var input of $(".timeday0until", clone)) {
input.name = "time[" + day + "][" + i + "][until]";
}
for (var select of $(".timeday0type", clone)) {
select.name = "time[" + day + "][" + i + "][type]";
}
for (var input of $(".timeday0from", clone)) {
input.value = "";
}
for (var input of $(".timeday0until", clone)) {
input.value = "";
}
for (var select of $(".timeday0type", clone)) {
select.value = "";
}
original.parentNode.appendChild(clone);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-lg-6 col-md-12">
<div class="well">
<h3>Day</h3>
<div class="row" id="day_0">
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0from" class="control-label">Interval starts</label>
<div class='input-group date' id='timeday0from'>
<input type="text" class="form-control datepicker timeday0from" name="time[day][0][from]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0until" class="control-label">Interval ends</label>
<div class='input-group date' id='timeday0until'>
<input type="text" class="form-control datepicker timeday0until" name="time[day][0][until]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-12">
<label for="timeday0info" class="control-label">Interval-Option</label>
<select name="time[day][0][info]" class="form-control timeday0type" id="timeday0info">
<option>Bitte auswählen</option>
</select>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-default" onclick="duplicateElement();"><span class="glyphicon glyphicon-plus"></span></button>
Creating works. But I do not have any idea, how to set maxDate, minDate and disabledTimeIntervals (overlapping of ranges should prevented) on clone/remove of elemen and update of a time-field.

What a mess - but it works!
$.fn.datetimepicker.defaults.tooltips = {
today: 'Heute',
clear: 'Auswahl leeren',
incrementMinute: 'später',
decrementMinute: 'früher',
incrementHour: 'später',
decrementHour: 'früher',
pickHour: 'Stunde wählen',
pickMinute: 'Minute wählen'
};
$.fn.datetimepicker.defaults.useCurrent = false;
$.fn.datetimepicker.defaults.ignoreReadonly = true;
$.fn.datetimepicker.defaults.allowInputToggle = true;
$.fn.datetimepicker.defaults.locale = 'de';
$.fn.datetimepicker.defaults.showClear = true;
$(document).ready(function() {
initDateTimePair('day',0);
updateMin('day',0);
updateMax('day',0);
});
var i = 0;
var original = document.getElementById('day' +'_'+ i);
function initDateTimePair(day, item){
$("#time"+day+item+"from").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
$("#time"+day+item+"until").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
}
function updateMax(day, item){
$("#time"+day+item+"from").on("dp.change", function(e) {
$("#time"+day+item+"until").data("DateTimePicker").minDate(e.date);
if($('#time'+day+item+'until').data("DateTimePicker")){
updateDisabledTimes(day, item);
}
});
}
function updateMin(day, item){
$("#time"+day+item+"until").on("dp.change", function(e) {
$("#time"+day+item+"from").data("DateTimePicker").maxDate(e.date);
if($('#time'+day+item+'from').data("DateTimePicker")){
updateDisabledTimes(day, item);
}
});
}
function initDisabledTimes(day, item){
var arr = collectDisabledTime(day, null);
$('#time'+day+item+'from').data("DateTimePicker").disabledTimeIntervals(arr);
$('#time'+day+item+'until').data("DateTimePicker").disabledTimeIntervals(arr);
}
function updateDisabledTimes(day, item){
for(l=0; l<=i; l++) {
var arr = collectDisabledTime(day, item);
if(l!=item){
$('#time'+day+l+'from').data("DateTimePicker").disabledTimeIntervals(arr);
$('#time'+day+l+'until').data("DateTimePicker").disabledTimeIntervals(arr);
}
}
}
function collectDisabledTime(day, item){
var arr = [];
for(j=0; j<=i; j++){
if(j!=item){
var from = $('#time'+day+j+'from').data("DateTimePicker");
var until = $('#time'+day+j+'until').data("DateTimePicker");
if(until !== undefined && until.date() !== null && from !== undefined && from.date() !== null){
arr.push([$('#time'+day+j+'from').data("DateTimePicker").date().add(1,'minute'), $('#time'+day+j+'until').data("DateTimePicker").date().add(-1,'minute')]);
}
}
}
return arr;
}
function duplicateElement(day) {
var clone = original.cloneNode(true);
i++;
clone.id = day + '_' + i; // there can only be one element with an ID
clone.childNodes;
for (var input of $(".time"+day+"from", clone)) {
input.id = "time" + day + i + "from";
}
for (var input of $(".time"+day+"until", clone)) {
input.id = "time" + day + i + "until";
}
for (var select of $(".time"+day+"type", clone)) {
select.id = "time" + day + i + "info";
}
for (var input of $(".time"+day+"from", clone)) {
input.name = "time[" + day + "][" + i + "][from]";
}
for (var input of $(".time"+day+"until", clone)) {
input.name = "time[" + day + "][" + i + "][until]";
}
for (var select of $(".time"+day+"type", clone)) {
select.name = "time[" + day + "][" + i + "][type]";
}
for (var input of $(".time"+day+"from", clone)) {
input.value = "";
}
for (var input of $(".time"+day+"until", clone)) {
input.value = "";
}
for (var select of $(".time"+day+"type", clone)) {
select.value = "-1";
}
original.parentNode.appendChild(clone);
initDateTimePair(day, i);
updateMin(day, i);
updateMax(day, i);
initDisabledTimes(day, i);
updateDisabledTimes(day, i);
console.log($('#timeday'+i+'from').data("DateTimePicker").disabledTimeIntervals())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/de.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="col-lg-6 col-md-12">
<div class="well">
<h3>Day</h3>
<div class="row" id="day_0">
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0from" class="control-label">Interval starts</label>
<div class='input-group date' id='timeday0from'>
<input type="text" class="form-control datepicker timedayfrom" name="time[day][0][from]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0until" class="control-label">Interval ends</label>
<div class='input-group date' id='timeday0until'>
<input type="text" class="form-control datepicker timedayuntil" name="time[day][0][until]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-12">
<label for="timeday0info" class="control-label">Interval-Option</label>
<select name="time[day][0][info]" class="form-control timedaytype" id="timeday0info">
<option value="-1">Bitte auswählen</option>
</select>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-default" onclick="duplicateElement('day');"><span class="glyphicon glyphicon-plus"></span></button>

Related

on plus icon dynamic textbox is not getting generated in jquery

What I want is, I want to generate a new input type = text whenever a plus icon is getting clicked. SO I have written below code for the same.
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
alert(numItems);
if (numItems != 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.substr(13, lastfieldsid.length));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata1" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata1" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'></i></div></td></tr>"
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
</div>
Couple of problem in your code.
Use slice(-1) to get last character of id. It's remove your dependency using hardcode substr(13,... and you can use that value to increase new generated id by +1 .
Check length for input using $('.form-group').find('input').length < 5 which check the length of input inside form-group class and user only able to add 5 inputs.
Finally don't forgot to append your generated element on form-group class using $('.form-group').append(tr); .
I also add example to delete added tr using minus class.
Example:
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
if ($('.form-group').find('input').length < 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.slice(-1));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'>Remove</i></div></td></tr>";
}
$('#yourid').append(tr);
} else {
alert("warning........")
}
}
$(document).on('click', 'div.minus', function() {
$(this).closest('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group" id="yourid">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true">icon</i>
</div>
</div>
Assuming that you are going to add new input field in div#dvDVRdata1. You need to append the HTMLcontent to that div as following:
$('#dvDVRdata1').append(tr);
The thing is you need to append the element, which you did not do in the code in your question.
As for remove, you also have not done it in your question yet. Here's the example of add and remove.
$(document).ready(function(){
$('.add').on('click', function () {
addDynamicTextbox();
});
$('.del').click(function (e) {
deleteDynamicTextbox(e);
});
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems != 5) {
var formGroup = $('.form-group');
var elem = `<div class="dvDVRdata" id="dvDVRdata${numItems+1}">
<label for="txtDVRAddress${numItems+1}">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress${numItems+1}" runat="server" />
</div>`;
formGroup.append(elem);
}
}
function deleteDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems > 1) {
$(`#dvDVRdata${numItems}`).remove();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/js/all.min.js" integrity="sha512-rpLlll167T5LJHwp0waJCh3ZRf7pO6IT1+LZOhAyP6phAirwchClbTZV3iqL3BMrVxIYRbzGTpli4rfxsCK6Vw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<div class="dvDVRdata" id="dvDVRdata1">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" />
</div>
</div>
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
<div class="del">
<i class="fa fa-minus" aria-hidden="true"></i>
</div>

Updated: How do I pass a default value into my modal input element

UPdated: have been stuck on this for 3 day's now and I cannot find an answer anywhere.
I have a model that contains -input type="text" name="mycardname" id="CardName"/-
I want to post the card name into the value of the input box.
I can put it in a label or a span, but cannot find a way or example to add it to the input box.
My code is below.
var ATTRIBUTES = ['cardname', 'metric', 'month'];
$('.CardModal').on('click', function (e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function (attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '');
$target('#CardName')('value try This');
});
});
$('#settingsModal,#monthModal').on('show.bs.modal', function (event) {
alert("this alert");
var $card = $(event.relatedTarget).closest('.card');
var $modal = $(this);
var data = $card.data();
Document.getElementById('#CardName').val("try This");
for (var item in data) {
$modal.find('[name="' + item + '"]').val(data[item]);
}
});
$('#monthModal .btn-primary').click(function () {
var $modal = $(this).closest('.modal');
var searchType = $modal.find('input[name="SearchTypeRadio"]:checked').val();
var metric = $modal.find('[name="metric"]').val();
var month = $modal.find('[name="month"]').val();
var cdName = $modal.find('[name="mycardname"]').val();
alert("SearchType: " + searchType + " Metric: " + metric + " Month: " + month + " Card Name: " + cdName);
});
$('.btnApplyColors').on('click', function () {
var $modal = $(this).closest('.modal');
var cardName = $modal.find('[name="name"]').val();
var grMin = $modal.find('[name="greenmin"]').val();
var grMax = $modal.find('[name="greenmax"]').val();
var yMin = $modal.find('[name="yellowmin"]').val();
var yMax = $modal.find('[name="yellowmax"]').val();
var rMin = $modal.find('[name="redmin"]').val();
var rMax = $modal.find('[name="redmax"]').val();
var cardTR = cardName + 'TR';
var elements = document.getElementsByClassName(cardTR); // get all elements
for (var i = 0; i < elements.length; i++) {
var tsd1 = cardName + i + 'TD1';
var tsd2 = cardName + i + 'TD2';
var td1 = document.getElementById(tsd1).innerHTML;
var td2 = parseInt(document.getElementById(tsd2).innerHTML);
alert(td1 + " - " + td2);
switch (true) {
case (td2 >= yMin && td2 <= yMax):
alert(td1 + " - " + td2 + " YMin " + yMin + " yMax " + yMax);
elements[i].style.backgroundColor = "lightyellow";
elements[i].style.color = 'brown';
break;
case (td2 >= grMin && td2 <= grMax):
alert(td1 + " - " + td2 + " grMin " + grMin + " grMax " + grMax);
elements[i].style.backgroundColor = "#E7FCE3";
elements[i].style.color = 'darkgreen';
break;
case (td2 >= rMin && td2 <= rMax):
alert(td1 + " - " + td2 + " rMin " + rMin + " rMax " + rMax);
elements[i].style.backgroundColor = "mistyrose";
elements[i].style.color = 'red';
break;
default:
alert("Hit the Default because " + td2 + " not found");
break;
}
}
$('#ScoreCardDefaults').modal('hide');
});
$(document).ready(function () {
$('input[type="radio"]').click(function () {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".box").not(targetBox).hide();
$(targetBox).show();
});
});
// clean this up //
let startYear = 2000;
let endYear = new Date().getFullYear();
for (i = endYear; i > startYear; i--) {
$('#yearpicker').append($('<option />').val(i).html(i));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row row-cols-1 row-cols-md-2 row-cols-xl-4">
<div class="col mb-4" data-mincoolscale="71">
<div class="card text-center" data-metric="14" data-month="2020-10" data-mincoolscale="71" data-maxcoolscale="100" data-minwarmscale="51" data-maxwarmscale="70" data-minhotscale="0" data-maxhotscale="50">
<div class="card-img-top d-flex align-items-center justify-content-center bg-primary text-light metric-header">
<span class="h5 my-1">my card</span>
</div>
<div class="card-body pt-3">
<h6 class="card-title">
my card title
</h6>
<p>
<span class="metric-date">#DateTime.Now.ToString("MMMM yyyy")</span>
<button type="button" class="btn btn-sm btn-link CardModal" data-cardname="The Card Name" data-toggle="modal" data-target="#monthModal" title="Edit" aria-title="Edit">
Ccc
</button>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="monthModal" tabindex="-1" aria-labelledby="monthModalTitle" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="monthModalTitle">Display Statistics For</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<span id="modal-cardname"></span>
<input type="text" name="mycardname" id="CardName" />
<div class="myRadios">
<label><input type="radio" name="SearchTypeRadio" value="Monthly"> Monthly</label>
<label><input type="radio" name="SearchTypeRadio" value="Quarterly"> Quarterly</label>
</div>
<div style="display:none" class="Monthly box">You have selected Monthly</div>
<div style="display:none" class="Quarterly box">You have selected quarterly</div>
<div style="display:none" class="Monthly box form-group">
<input type="month" id="month" name="month" class="form-control w-auto" placeholder="mm/yyyy" max="#DateTime.Now.ToString("yyyy-MM")" min="2010-01" />
</div>
<div style="display:none" class="Quarterly box form-group">
#*<label for="month">Yearly Quarter of</label>*#
<select id="QTRS">
<option value="1" selected>1st Quarter</option>
<option value="2">2nd Quarter</option>
<option value="3">3rd Quarter</option>
<option value="4">4th Quarter</option>
</select>
<select name="yearpicker" id="yearpicker"></select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
#*<a class=" btn btn-primary" asp-controller="Home" asp-action="updateSSOA"> Apply</a>*#
<button type="button" class="btn btn-primary" data-dismiss="modal">Apply</button>
</div>
</div>
</div>
</div>
I don’t know if there are multiple text boxes and buttons that are the same on this page. Do you mean to traverse all ATTRIBUTES to the text box corresponding to this button or to pass the ATTRIBUTES corresponding to the modal value into the text box?
If you pass in a corresponding ATTRIBUTES, please refer to the following example:
<input type="text" name="mycardname" id="CardName" />
<button type="button" class="btn btn-sm btn-link CardModal"
data-cardname="kls01" data-toggle="modal" data-target="#monthModal"
title="Edit" aria-title="Edit">
Launch Modal
</button>
#section Scripts{
<script>
$(function () {
var ATTRIBUTES = ['cardname', 'metric', 'month'];
$('.CardModal').on('click', function (e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function (attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '00');
if ($target.prev().val() == '' || $target.prev().val == null) {
$target.prev().val(attributeName || '')
}
});
});
})
</script>
}
Result:
I finally figured it out:
Change:
$target('#CardName')('value try This');
to:
var myCardName = $(this).data('cardname');
$(".modal-body #mycardname").val(myCardName);

how to delete the inserted row by the delete button

I am trying to delete the entered task by the delete button which is created by the end of each task. I am posting my full code here
It's a simple to-do list by using bootstrap CDN .
I want to delete the row which contains user enter task,serial number,time and date.
var task = document.getElementById("enter");
var bttn = document.getElementById("button2");
var rowIdVar = document.getElementById("test");
var rowIdVar1 = document.getElementById("id1");
bttn.addEventListener("click", add);
var x = 0;
function add() {
var val1 = task.value;
if (!val1) {
alert("Please Enter A Task");
} else {
sno();
name();
tdate();
time();
cButton();
var new1 = document.createElement("l");
rowIdVar1.appendChild(new1);
}
}
function sno() {
if (x == x) {
x = x + 1;
var list1 = document.createElement("l");
list1.innerHTML = x;
rowIdVar.appendChild(list1).setAttribute("class", "col-md-2");
}
}
function name() {
var val = task.value;
var list2 = document.createElement("l");
list2.innerHTML = val;
rowIdVar.appendChild(list2).setAttribute("class", "col-md-4");
task.value = "";
}
function tdate() {
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var result = (date + "/" + month + "/" + year);
var lm = document.createElement("l");
lm.innerHTML = result;
rowIdVar.appendChild(lm).setAttribute("class", "col-md-2");
}
function time() {
var t = new Date();
var hour = t.getHours();
var minutes = t.getMinutes();
var seconds = t.getSeconds();
var result1 = (hour + ":" + minutes + ":" + seconds);
var lm1 = document.createElement("l");
lm1.innerHTML = result1;
rowIdVar.appendChild(lm1).setAttribute("class", "col-md-2");
}
function cButton() {
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "delete");
btn.setAttribute("class", "btn btn-danger");
rowIdVar.appendChild(btn).setAttribute("class", "col-md-2");
btn.addEventListener("click", deleteElements);
}
function deleteElements() {
rowIdVar1.parentNode.removeChild(rowIdVar);
}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<body>
<div class="row">
<div class="col-md-10 col-sm-10 h">
<center>
<h1>TO DO LIST...</h1>
</center><br>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-10 col-sm-10 bg">
<input type="text" class="form-control " placeholder="Enter task" id="enter">
</div>
<div class="col-md-2 col-sm=2">
<button type="button" class="btn btn-primary btn-lg" id="button2"><center>ADD</center></button>
</div>
</div><br><br>
</div>
<div class="container">
<div class="row" id="id1">
<div class="col-md-2 b">
<h1>S.no</h1>
</div>
<div class="col-md-4 b">
<h1>Enter Task</h1>
</div>
<div class="col-md-2 b">
<h1>Date</h1>
</div>
<div class="col-md-2 b">
<h1>Time</h1>
</div>
<div class="col-md-2">
</div>
</div>
</div>
<div class="row" id="test">
<div class="col-md-2"> </div>
<div class="col-md-4"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
</div>
var task = document.getElementById("enter");
var bttn = document.getElementById("button2");
var rowIdVar = document.getElementById("test");
var rowIdVar1 = document.getElementById("id1");
bttn.addEventListener("click", add);
var x = 0;
function add() {
var val1 = task.value;
if (!val1) {
alert("Please Enter A Task");
} else {
sno();
name();
tdate();
time();
cButton();
var new1 = document.createElement("l");
rowIdVar1.appendChild(new1);
}
}
function sno() {
if (x == x) {
x = x + 1;
var list1 = document.createElement("li");
list1.innerHTML = x;
rowIdVar.appendChild(list1).setAttribute("class", "col-md-2");
}
}
function name() {
var val = task.value;
var list2 = document.createElement("li");
list2.innerHTML = val;
rowIdVar.appendChild(list2).setAttribute("class", "col-md-4");
task.value = "";
}
function tdate() {
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var year = d.getFullYear();
var result = (date + "/" + month + "/" + year);
var lm = document.createElement("li");
lm.innerHTML = result;
rowIdVar.appendChild(lm).setAttribute("class", "col-md-2");
}
function time() {
var t = new Date();
var hour = t.getHours();
var minutes = t.getMinutes();
var seconds = t.getSeconds();
var result1 = (hour + ":" + minutes + ":" + seconds);
var lm1 = document.createElement("li");
lm1.innerHTML = result1;
rowIdVar.appendChild(lm1).setAttribute("class", "col-md-2");
}
function cButton() {
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "delete");
btn.setAttribute("class", "btn btn-danger");
rowIdVar.appendChild(btn).setAttribute("class", "col-md-2");
btn.addEventListener("click", deleteElements);
}
function deleteElements() {
rowIdVar.parentNode.removeChild(rowIdVar);
}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" rel="stylesheet"/>
<body id="body">
<div class="row">
<div class="col-md-10 col-sm-10 h">
<center>
<h1>TO DO LIST...</h1>
</center><br>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-10 col-sm-10 bg">
<input type="text" class="form-control " placeholder="Enter task" id="enter">
</div>
<div class="col-md-2 col-sm=2">
<button type="button" class="btn btn-primary btn-lg" id="button2"><center>ADD</center></button>
</div>
</div><br><br>
</div>
<div class="container">
<div class="row" id="id1">
<div class="col-md-2 b">
<h1>S.no</h1>
</div>
<div class="col-md-4 b">
<h1>Enter Task</h1>
</div>
<div class="col-md-2 b">
<h1>Date</h1>
</div>
<div class="col-md-2 b">
<h1>Time</h1>
</div>
<div class="col-md-2">
</div>
</div>
</div>
<div class="row" id="test">
<div class="col-md-2"> </div>
<div class="col-md-4"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
<div class="col-md-2"> </div>
</div>

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>

"Undefined" shown in last column while populating JSON data

I have converted a csv to JSON object and have populated it on a html table. Rest of the columns are fine but the last column of the table shows 'Undefined'. CSV file -
The table displayed as-
What is the problem here?
HTML file-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>Japan Automation</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
<!--<script type="text/javascript" src="JavaScript.js"></script>-->
<script type="text/javascript" src="JavaScript4.js"></script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
th {
text-align: left;
}
table {
border-spacing: 5px;
}
.guide {
text-decoration: underline;
text-align: center;
}
.odd {
color: #fff;
background: #666;
}
.even {
color: #666;
}
.hot {
border: 1px solid #f00;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<h2>Global Order Visibility</h2>
</div>
<div class="panel panel-primary">
<div class="panel-heading">Japan Automation Tool</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12 col-sm-offset-1">
<form id="form1" runat="server" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5">
<div class="col-sm-6">
<input type="file" accept=".csv" id="fileUpload" />
</div>
<div class="col-sm-6">
<input type="button" id="upload" class="btn btn-primary" value="Upload" />
</div>
</div>
<div class="col-sm-7">
<div class="col-sm-2">
<input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" />
</div>
<div class="col-sm-2">
<input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" />
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12">
<center>
<div class="input-append" id="filterDev" style="visibility:hidden">
<input name="search" id="inputFilter" placeholder="Enter ID to filter" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></center>
</div>
<br />
<br />
</div>
<div class="row">
<div class="col-sm-12" id="dvCSV">
<table id="my-table">
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="download" style="color: cornflowerblue; visibility: hidden"><strong>Please click the below links to download the processed file..</strong></p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3">
<p id="File1" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File1 Download</p>
</div>
<div class="col-sm-3">
<p id="File2" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File2 Download</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$("#cancel").on("click", function () {
$('input:checked').each(function () {
$(this).closest("tr").remove();
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
document.getElementById("download").style.visibility = "visible";
});
});
$("#filter").click(function () {
ids = $("#inputFilter").val();
if (ids != "") {
idsArray = ids.split(",");
$("#my-table tr:gt(0)").hide();
$.each(idsArray, function (i, v) {
$("#my-table tr[data-id=" + v + "]").show();
})
} else {
$("#my-table tr").show();
}
});
</script>
JavaScript4.js
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
//var table = $("<table id='name'/>");
var lines = e.target.result.split("\n");
var result = [];
var headers = lines[0].split(",");
//alert(headers);
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
populateTable(result);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
}
}
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
});
});
function populateTable(finalObject) {
var obj = finalObject;
var table = $("<table id='my-table' />");
table[0].border = "1";
var columns = Object.keys(obj[0]);
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
var headerCell = $("<th />");
headerCell.html([columns[i]]);
row.append(headerCell);
}
$.each(obj, function (i, obj) {
//row = '<tr data-id="' + obj.ID + '"><td>' + obj.ID + '</td><td>' + obj.NAME + '</td><td>' + obj.CITY + '</td><td>' + obj.ADDRESS + '</td></tr>';
row = '<tr data-id="' + obj.ID + '"><td>' + obj.ID + '</td><td>' + obj.NAME + '</td><td>' + obj.CITY + '</td><td>' + obj.ADDRESS + '</td></tr>';
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
UPDATE ...
Line breaks where messing up with the ADDRESS property. Just remove all line breaks before using the strings and you will be fine:
var headers = lines[0].split(",");
for (var i = 1; i < headers.length; i++) {
var header = headers[i];
header = header.replace(/(\r\n|\n|\r)/gm,"");
headers[i] = header;
}
DEMO: http://jsbin.com/hatasaf/3/edit?js,output
I really could not find out why the ADDRESS property was being wrapped around quotes and being inaccessible, but an array fixed the problem ...
I'll investigate more to isolate the issue but for your purposes just use the code in the demo http://jsbin.com/hatasaf/2/edit?js,output
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var lines = e.target.result.split("\n");
var result = [];
for (var i = 0; i < lines.length; i++) {
var arr = [];
var currentline = lines[i].split(",");
for (var j = 0; j < currentline.length; j++) {
arr.push(currentline[j]);
}
result.push(arr);
}
populateTable(result);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
}
}
});
function populateTable(finalArray) {
var table = $("<table id='my-table' />");
table[0].border = "1";
var columns = finalArray[0];
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var j = 0; j < columns.length; j++) {
var headerCell = $("<th>").text([columns[j]]);
row.append(headerCell);
}
for (var i = 1; i < finalArray.length; i++) {
var item = finalArray[i];
row = '<tr data-id="' + item[0] + '"><td>' + item[0] + '</td><td>' + item[1] + '</td><td>' + item[2] + '</td><td>' + item[3] + '</td></tr>';
table.append(row);
};
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}

Categories

Resources