Append html content for each item in array - javascript

I'm working on a plugin and need to load the preset and fill out a form with this data. While trying to write the code as short as possible and to my knowledge, I ended up with creating a "template" variable as this:
var Fields =
'<div class="Container">' +
'<div class="Fields">' +
'<input type="text" name="Title" placeholder="Title" />' +
'<input type="text" name="Address" placeholder="Address" />' +
'<input type="text" name="Latitude" placeholder="Latitude" />' +
'<input type="text" name="Longitude" placeholder="Longitude" />' +
'<input type="text" name="Description" placeholder="Description" />' +
'<input type="text" name="URL" placeholder="URL" />' +
'<div class="Image"></div>' +
'</div>' +
'</div>';
And append it like so:
$('.results').append($(Fields))
.find('.Title').text(temp[0]).end()
.find('input[name="Title"]').val(temp[0]).end()
.find('input[name="Address"]').val(temp[1]).end()
.find('input[name="Latitude"]').val(temp[2]).end()
.find('input[name="Longitude"]').val(temp[3]).end()
.find('input[name="Description"]').val(temp[4]).end()
.find('input[name="URL"]').val(temp[5]).end()
.find('.Image')
.addClass('added-image')
.append('<img src="' + temp[6] + '" />').end();
The problem I'm facing is that all the data (except the image), is the same. When I console.log it shows two sets of data, but still title and so on is the same. Here is my entire function for setting preset:
function preset() {
var str = 'Stackoverflow&%1600 Penn&%10.2342342&%2.2532452&%Need help with this&%http://www.stackoverflow.com&%http://upload.wikimedia.org/wikipedia/commons/b/b2/Hausziege_04.jpg;Google&%Silicon Valley 1&%80.435234523&%14.0065592&%This is Google&%http://www.google.com&%http://resources.news.com.au/files/2012/01/13/1226243/386315-harp-seal-1.jpg;',
arr = {},
temp = {},
Fields =
'<div class="Container">' +
'<div class="Fields">' +
'<input type="text" name="Title" placeholder="Title" />' +
'<input type="text" name="Address" placeholder="Address" />' +
'<input type="text" name="Latitude" placeholder="Latitude" />' +
'<input type="text" name="Longitude" placeholder="Longitude" />' +
'<input type="text" name="Description" placeholder="Description" />' +
'<input type="text" name="URL" placeholder="URL" />' +
'<div class="Image"></div>' +
'</div>' +
'</div>';
arr = str.split(";");
$.each(arr,function(i,val){
temp = arr[i].split("&%");
if(temp.length >= 2) {
if(temp[6] !== 'undefined') {
$('.results').append($(Fields))
.find('.Title').text(temp[0]).end()
.find('input[name="Title"]').val(temp[0]).end()
.find('input[name="Address"]').val(temp[1]).end()
.find('input[name="Latitude"]').val(temp[2]).end()
.find('input[name="Longitude"]').val(temp[3]).end()
.find('input[name="Description"]').val(temp[4]).end()
.find('input[name="URL"]').val(temp[5]).end()
.find('.Image')
.addClass('added-image')
.append('<img src="' + temp[6] + '" />').end();
} else {
$('.results').append($(Fields))
.find('.Title').text(temp[0]).end()
.find('input[name="Title"]').val(temp[0]).end()
.find('input[name="Address"]').val(temp[1]).end()
.find('input[name="Latitude"]').val(temp[2]).end()
.find('input[name="Longitude"]').val(temp[3]).end()
.find('input[name="Description"]').val(temp[4]).end()
.find('input[name="URL"]').val(temp[5]).end();
}
} else {
$('.results').append(Fields);
}
});
}
I have created a JSFiddle for those who wants to see the result up close, and easier giving me some pointers. http://jsfiddle.net/p7r2n18k/1/

The apppend function appends your fields and returns the element which data was appended to, so it ends up changing all of the fields including older ones.
Seperate the append function from the data update:
var fields = $(Fields);
$('.results').append(fields);
fields
.find('.Title').text(temp[0]).end()
...
Check this fiddle

Related

How to handle auto-populate dropdown for dynamic table row in JavaScript?

I am working on adding dynamic table rows. There is a button for adding table rows when a user clicks on that button. So there I have three dropdowns. Each dropdown have some ID. So I have implemented the things where I am trying to auto populate first dropdown on that button click. So I am clicking add more rows then for second row, empty dropdown is created.
I want that whenever a user clicks on add more rows, then each dropdown of rows should be auto-populated. I hope that I am clear with my words.
Below is the script to load data in dropdown and to create rows dynamically:
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
var url = "api/get/activecompany";
$.post(url, {
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var option = "<option selected disabled>Select Company</option>";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
var content = "<option value='"+list[i].companyid+"'>"+list[i].companyname+" <span>("+list[i].dotnumber+")</span></option>";
option = option + content;
}
}
document.getElementById('lcompanyselect').innerHTML = option;
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
});
$("body").on("click", ".remove", function() {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
return '<td class="">'+'<select class="js-example-placeholder-single js-states form-control" id="lcompanyselect" onchange="getDriverAndTruck()";></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_co"></td>'
+'<td><select class="js-example-placeholder-single js-states form-control" id="ldriverselect"></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_driver"></td>'
+'<td class=""><select class="js-example-placeholder-single js-states form-control" id="ltruckselect"></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_truck"></td>'
+ '<td><input name = "tripnumber" type="text" class="form-control" id="ltripnumber"/></td>'
+'<td><select id="lsubtrip" name="subtrip" class="js-example-placeholder-single js-states form-control"><option disabled selected></option>'
+'<option value="1">1</option><option value="2">2</option><option value="3">3</option></select>'
+ '<td><input name = "date" type="date" class="form-control" id="ldate"/></td>'
+ '<td><input name = "pickupcity" type="date" class="form-control" id="lpickupcity"/></td>'
+ '<td><input name = "pickupstate" type="date" class="form-control" id="lpickupstate"/></td>'
+ '<td><input name = "deliverydate" type="date" class="form-control" id="ldeliverydate"/></td>'
+ '<td><input name = "delivercity" type="text" class="form-control" id="ldelivercity"/></td>'
+ '<td><input name = "deliverstate" type="text" class="form-control" id="ldeliverstate"/></td>'
+ '<td><input name = "loadnumber" type="text" class="form-control" id="lloadnumber"/></td>'
+ '<td><input name = "loadrate" type="text" class="form-control" id="lloadrate" onkeyup="lcount();"/><span id="lerrormessage"></span></td>'
+ '<td><input name = "dispatchfee" type="text" class="form-control" id="ldispatchfee" readonly/></td>'
+ '<td><input name = "fuel" type="text" class="form-control" id="lfuel"/></td>'
+ '<td><input name = "cardfee" type="text" class="form-control" id="lcardfee"/></td>'
+ '<td><input name = "onloadrepair" type="text" class="form-control" id="lonloadrepair"/></td>'
+ '<td><input name = "shoprepair" type="text" class="form-control" id="lshoprepair"/></td>'
+ '<td><input name = "trailerrent" type="text" class="form-control" id="ltrailerrent"/></td>'
+ '<td><input name = "comcheck" type="text" class="form-control" id="lcomcheck"/></td>'
+ '<td><input name = "advance" type="text" class="form-control" id="ladvance"/></td>'
+ '<td><input name = "miscellenous" type="text" class="form-control" id="lmiscellenous"/></td>'
+ '<td><input name = "misc1" type="text" class="form-control" id="lmisc1"/></td>'
+ '<td><input name = "misc2" type="text" class="form-control" id="lmisc2"/></td>'
+ '<td><input name = "misc3" type="text" class="form-control" id="lmisc3"/></td>'
+ '<td><input name = "misc4" type="text" class="form-control" id="lmisc4"/></td>'
+ '<td><input name = "total" type="text" class="form-control" id="ltotal" readonly/></td>'
+ '<td><input name = "layover" type="text" class="form-control" id="llayover"/></td>'
+ '<td><input name = "addtl1" type="text" class="form-control" id="laddtl1"/></td>'
+ '<td><input name = "addtl2" type="text" class="form-control" id="laddtl2"/></td>'
+ '<td><input name = "addtl3" type="text" class="form-control" id="laddtl3"/></td>'
+ '<td><input name = "subtotal" type="text" class="form-control" id="lsubtotal" readonly/></td>'
+ '<td><input name = "paymentmode" type="text" class="form-control" id="lpaymentmode"/></td>'
+ '<td><input name = "pay" type="text" class="form-control" id="lpay"/></td>'
+ '<td><input name = "notes" type="text" class="form-control" id="lnotes"/></td>'
+ '<td><input name = "grandtotal" type="text" class="form-control" id="lgrandtotal" readonly/></td>'
+ '<td><button type="button" class="btn btn-outline-info text-info" onclick="savetriplist();">Submit</button>'
+'<button type="button" class="btn btn-outline-danger text-danger remove">Remove</button></td>'
}
The one thing I have observed in your code is, its looking for a dropdown with id as lcompanyselect and then fills it with options. when the code runs for the first time it adds the dropdown on the dom, but when the code runs second time (when add button clicked) its filling the same dropdown which was added earlier, because the code is looking for element with id as lcompanyselect and it has found one.
document.getElementById('lcompanyselect').innerHTML = option;
Instead, I would suggest to have a placeholder for dropdown in your, function
GetDynamicTextBox(value)
<select class="js-example-placeholder-single js-states form-control" id="lcompanyselect" onchange="getDriverAndTruck()";>{Placeholder}</select>
and in code when you are finding the element, instead replace the {placeholder} with options html.
This is how modified code looks.
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<tr />");
var dynamicTextboxHtml = div.html(GetDynamicTextBox(""));
var url = "api/get/activecompany";
$.post(url, {
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var option = "<option selected disabled>Select Company</option>";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
var content = "<option value='"+list[i].companyid+"'>"+list[i].companyname+" <span>("+list[i].dotnumber+")</span></option>";
option = option + content;
}
}
dynamicTextboxHtml.replace("{OptionsPlaceholder}",content);
$("#TextBoxContainer").append(dynamicTextboxHtml);
dynamicTextboxHtml = '';
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
});
$("body").on("click", ".remove", function() {
$(this).closest("tr").remove();
});
});
function GetDynamicTextBox(value) {
return '<td class="">'+'<select class="js-example-placeholder-single js-states form-control" id="lcompanyselect" onchange="getDriverAndTruck()";>{OptionsPlaceholder}</select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_co"></td>'
+'<td><select class="js-example-placeholder-single js-states form-control" id="ldriverselect"></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_driver"></td>'
+'<td class=""><select class="js-example-placeholder-single js-states form-control" id="ltruckselect"></select>'
+'<input type="button" value="+" class="qty-plus" data-toggle="modal" data-target="#edit_truck"></td>'
+ '<td><input name = "tripnumber" type="text" class="form-control" id="ltripnumber"/></td>'
+'<td><select id="lsubtrip" name="subtrip" class="js-example-placeholder-single js-states form-control"><option disabled selected></option>'
+'<option value="1">1</option><option value="2">2</option><option value="3">3</option></select>'
+ '<td><input name = "date" type="date" class="form-control" id="ldate"/></td>'
+ '<td><input name = "pickupcity" type="date" class="form-control" id="lpickupcity"/></td>'
+ '<td><input name = "pickupstate" type="date" class="form-control" id="lpickupstate"/></td>'
+ '<td><input name = "deliverydate" type="date" class="form-control" id="ldeliverydate"/></td>'
+ '<td><input name = "delivercity" type="text" class="form-control" id="ldelivercity"/></td>'
+ '<td><input name = "deliverstate" type="text" class="form-control" id="ldeliverstate"/></td>'
+ '<td><input name = "loadnumber" type="text" class="form-control" id="lloadnumber"/></td>'
+ '<td><input name = "loadrate" type="text" class="form-control" id="lloadrate" onkeyup="lcount();"/><span id="lerrormessage"></span></td>'
+ '<td><input name = "dispatchfee" type="text" class="form-control" id="ldispatchfee" readonly/></td>'
+ '<td><input name = "fuel" type="text" class="form-control" id="lfuel"/></td>'
+ '<td><input name = "cardfee" type="text" class="form-control" id="lcardfee"/></td>'
+ '<td><input name = "onloadrepair" type="text" class="form-control" id="lonloadrepair"/></td>'
+ '<td><input name = "shoprepair" type="text" class="form-control" id="lshoprepair"/></td>'
+ '<td><input name = "trailerrent" type="text" class="form-control" id="ltrailerrent"/></td>'
+ '<td><input name = "comcheck" type="text" class="form-control" id="lcomcheck"/></td>'
+ '<td><input name = "advance" type="text" class="form-control" id="ladvance"/></td>'
+ '<td><input name = "miscellenous" type="text" class="form-control" id="lmiscellenous"/></td>'
+ '<td><input name = "misc1" type="text" class="form-control" id="lmisc1"/></td>'
+ '<td><input name = "misc2" type="text" class="form-control" id="lmisc2"/></td>'
+ '<td><input name = "misc3" type="text" class="form-control" id="lmisc3"/></td>'
+ '<td><input name = "misc4" type="text" class="form-control" id="lmisc4"/></td>'
+ '<td><input name = "total" type="text" class="form-control" id="ltotal" readonly/></td>'
+ '<td><input name = "layover" type="text" class="form-control" id="llayover"/></td>'
+ '<td><input name = "addtl1" type="text" class="form-control" id="laddtl1"/></td>'
+ '<td><input name = "addtl2" type="text" class="form-control" id="laddtl2"/></td>'
+ '<td><input name = "addtl3" type="text" class="form-control" id="laddtl3"/></td>'
+ '<td><input name = "subtotal" type="text" class="form-control" id="lsubtotal" readonly/></td>'
+ '<td><input name = "paymentmode" type="text" class="form-control" id="lpaymentmode"/></td>'
+ '<td><input name = "pay" type="text" class="form-control" id="lpay"/></td>'
+ '<td><input name = "notes" type="text" class="form-control" id="lnotes"/></td>'
+ '<td><input name = "grandtotal" type="text" class="form-control" id="lgrandtotal" readonly/></td>'
+ '<td><button type="button" class="btn btn-outline-info text-info" onclick="savetriplist();">Submit</button>'
+'<button type="button" class="btn btn-outline-danger text-danger remove">Remove</button></td>'
}

unable to submit properly Dynamic created forms using jQuery

hi I am creating dynamic forms using jquery like this
function testagenda(id){
$("#AppendAgendaForm").append(' <form method="POST" id=+'id'+"
enctype="multipart/form-data" >\n' +
'{% csrf_token %}\n' +
'<!--date field-->\n' +'<div class="row mb-3 mt-3">\n' +
'<div class="col-md-1"></div>\n' +
'<div class="col-md-2">\n' +
'<h5 style="margin-top:32px;">Date</h5>\n' +
'</div>\n' +
'<div class="col-md-3">\n' +
'<label>From</label>\n' +
'<input autocomplete="off" name="startDate" type="text" id="dt1" class="form-control" placeholder="from" required>\n' +
'{#<!-- <input type="date" class="form-control" value="{{ finalizedDate.startDate|date:\'Y-m-d\' }}" id="fromvalidity" name="fromvalidity" required/>-->#}\n' +
'</div>\n' +
'<div class="col-md-3">\n' +
' <label>To</label>\n' +
'<input autocomplete="off" name="endDate" type="text" id="dt2" class="form-control" placeholder="To" required>\n' +
'{#<!--<input type="date" class="form-control" value="{{ finalizedDate.endData|date:\'Y-m-d\' }}" id="tovalidity" name="tovalidity" required/>-->#}\n' +
'</div>\n' +
'<div class="col-md-3"></div>\n' +
'</div>\n' +
'</form>\n' +
'\n');
}
as I have diff Id for every form . And Use can create even more then 100 forms . Now How I Can submit every form Independently using max 1 function etc ?
best way in case was getting ID first using document.getElementbyID on Click . then form(FormID).submit()

how to pass multiple files and a json object in single post request

I struggled for two days but not quite solution I found. Here is the scenario:
I have .NET MVC project and in current view user can add multiple rows by clicking "Add new Row". Each row contains 4 input type="text" and 1 input type="file". it is working absolutely fine.
Problem is happening when I post this form to my MVC controller. I am receiving all data at my MVC controller except Files that are uploaded in each row. This is how I am doing it.
View:
<div class="row p-t-20">
<div class="col-md-2">
<div class="form-group">
<label class="control-label">Transaction Date</label>
<input type="text" name="TransactionDate1" id="mdate1" class="form-control tdate01" value="" required />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="control-label">Description</label>
<textarea name="Description1" id="Description1" class="form-control descr01" cols="2" rows="2"></textarea>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="control-label">Amount</label>
<input type="text" name="Amount1" id="Amount1" class="form-control amt01" required />
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="control-label">Invoice #</label>
<input type="text" name="InvoiceNo1" id="InvoiceNo1" class="form-control inv01" required />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="control-label">Comments</label>
<textarea name="Comments1" id="Comments1" class="form-control comm01" cols="1" rows="2"></textarea>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Upload Invoice</label>
<input type="file" name="postedFile1" id="postedFile1" class="form-control file01" required />
<input type="hidden" name="hiddenfile1" id="hiddenfile1" value=""/>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<br />
<input type="button" id="btnAdd" value="+ Row" class="btn btn-dark" />
</div>
</div>
</div>
<div class="form-actions m-t-40">
**<button type="button" id="btnSubmit" class="btn btn-success"> <i class="fa fa-check"></i> Save</button>**
</div>
jQuery Code
var rowCount; var transactionDetailVM = []; var ClaimTransactionVM = {}; var reimFiles = []; var fileString = ''; var reader;
$(document).ready(function () {
debugger;
rowCount = 1;
$(document).on("click", "#btnAdd", function () { //
// var rowCount = $('.data-contact-person').length + 1;
//Generating base64 string for previously uploaded file.
//var filelogoUpload = $('#postedFile' + rowCount).get(0);
//var files = filelogoUpload.files;
//var file = files[0]; getBase64(file, rowCount);
rowCount++;
//Validations will run before adding a new row.
var rowdiv = '<div class="row p-t-20">'
+ '<div class="col-md-2"> '
+ ' <div class="form-group"> '
+ ' <label class="control-label">Transaction Date</label>'
+ ' <input type="text" name="TransactionDate' + rowCount + '" id="mdate' + rowCount +'" class="form-control tdate01" value="" required />'
+ ' </div>'
+ ' </div>'
+ '<div class="col-md-2" >'
+ ' <div class="form-group">'
+ ' <label class="control-label">Description</label>'
+ '<textarea name="Description' + rowCount +'" id="Description' + rowCount +'" class="form-control descr01" cols="2" rows="2"></textarea>'
+ '</div>'
+ '</div>'
+ '<div class="col-md-1">'
+ '<div class="form-group">'
+ '<label class="control-label">Amount</label>'
+ ' <input type="text" name="Amount' + rowCount + '" id="Amount' + rowCount +'" class="form-control amt01" />'
+ '</div>'
+ '</div>'
+ '<div class="col-md-1" >'
+ '<div class="form-group">'
+ '<label class="control-label">Invoice #</label>'
+ '<input type="text" name="InvoiceNo' + rowCount + '" id="InvoiceNo' + rowCount +'" class="form-control inv01" />'
+ '</div>'
+ '</div>'
+ '<div class="col-md-2" >'
+ '<div class="form-group">'
+ '<label class="control-label">Comments</label>'
+ '<textarea name="Comments' + rowCount +'" id="Comments' + rowCount +'" class="form-control comm01" cols="1" rows="2"></textarea>'
+ ' </div></div>'
+ '<div class="col-md-2">'
+ '<div class="form-group">'
+ ' <label>Upload Invoice</label>'
+ '<input type="file" name="postedFile' + rowCount + '" id="postedFile' + rowCount + '" class="form-control file01" />'
//+ '<input type="hidden" name="hiddenfile' + rowCount + '" id="hiddenfile' + rowCount+'"/>'
+ '</div>'
+ '</div>'
+ '<div class="col-md-2">'
+'<div class="form-group">'
+ '<input type="button" id="btnAdd" value="+ Row" class="btn btn-dark" />'
+ '<input type = "button" id ="btnRemove" value="- Row" class="btn btn-danger" />'
+'</div>'
+'</div>'
+'</div>';
$('#newClaimForm').append(rowdiv);
debugger;
//$("input[name*='TransactionDate']").css("background-color", "yellow");
// Adding these controls to Main table class
});
});
$(document).on("click", "#btnRemove", function () {
$(this).closest("div[class='row p-t-20']").remove();
});
function getAllData() {
console.log('getalldata called');
var claimTitle = $('#TransactionName').val();
var claimType = $('#ClaimTypes').val();
//Transaction Details
for (var i = 1; i <= rowCount; i++) {
//file operation
var filelogoUpload = $('#postedFile' + i).get(0);
var files = filelogoUpload.files;
var file = files[0]; //getBase64(file);
//reader = new FileReader();
//reader.onload = function () {
// //console.log(reader.result);
// fileString = reader.result;
//};
//reader.readAsDataURL(file);
//end file operation
var trandate = $('#mdate' + i).val();
var descr = $('#Description' + i).val();
var amt = $('#Amount' + i).val();
var invno = $('#InvoiceNo'+i).val();
var comm = $('#Comments' + i).val();
//var baseFileString = $('#hiddenFile' + i).val();
debugger;
console.log(trandate);
console.log(descr);
console.log(amt);
console.log(invno);
console.log(comm);
console.log(file);
var transactionDetails = {
TransactionDate: trandate,
Description: descr,
Amount: amt,
InvoiceNumber: invno,
Comments: comm,
baseFile: file
}
//console.log('Transaction Object:' + transactionDetails);
//filled transaction Detail array
transactionDetailVM.push(transactionDetails);
console.log(transactionDetailVM);
//reimFiles.push(file);
}
//filled model
ClaimTransactionVM = {
TransactionName: claimTitle,
ClaimType: claimType,
TransactionDetails: transactionDetailVM
};
// console.log('Model:'+ClaimTransactionVM);
}
$("#btnSubmit").click(function SaveReimbursements() {
//Validations will run
console.log('Save button called');
debugger;
getAllData();
if (ClaimTransactionVM !== null) {
var FormClaims = new FormData();
FormClaims.append('currentClaim', JSON.stringify(ClaimTransactionVM));
//FormClaims.append()
//console.log(ClaimTransactionVM);
//var data = {
// currentClaim: ClaimTransactionVM,
// files: reimFiles
//}
$.ajax({
url: '/ClaimProcess/CreateClaim',
type: 'POST',
processData: false,
contentType: 'application/json',
data: FormClaims,//JSON.stringify(ClaimTransactionVM),
success: function (response) {
if (response === true) {
console.log('Success: IsSuccess True called');
swal({
title: 'success',
text: "Claim Added Successfully.",
type: "success",
confirmButtonColor: "#007AFF"
});
}
else if (response === false) {
console.log('Success: IsSuccess False called');
swal({
title: "Error!",
text: '',
type: "warning",
confirmButtonColor: "#DD6B55",
confirmButtonText: "Ok"
});
}
}
});
}
else
console.log('Model is empty.')
});
my final JSON object which needs to be passed is 'ClaimTransactionVM' which carries LIST of transaction details (each row that is added dynamically) and some other parameters.
I have tried following things already:
Used var reader = new FileReader(); and convert the file into base64 string and pass it in Json object. it works great in debug mode but in real-time reader.result doesn't get passed. no idea why. tried almost everything like recurring function to add delay to asynchronous code till my object gets filled. but no go.
Form data: used JSON.stringify to convertt the final Json object, it does pass but File doesn't get converted to HTTPPostedFileBase object. it skips the file while other params are received.
I would like to know how to send multiple Files and this JSON object together in my POST call.
I ran your code, fixed some errors noticed and also fixed the upload, it uploads a base64 string now. At your .NET MVC, you change handle the base64 string and save it as a file.
Updated Code:
var rowCount; var transactionDetailVM = []; var ClaimTransactionVM = {}; var reimFiles = []; var fileString = ''; var reader; var preview = '';
$(document).ready(function () {
rowCount = 1;
$("#btnAdd").click(function () { //
rowCount++;
//Validations will run before adding a new row.
var rowdiv = '<div class="row p-t-20">'
+ '<div class="col-md-2"> '
+ ' <div class="form-group"> '
+ ' <label class="control-label">Transaction Date</label>'
+ ' <input type="text" name="TransactionDate' + rowCount + '" id="mdate' + rowCount +'" class="form-control tdate01" value="" required />'
+ ' </div>'
+ ' </div>'
+ '<div class="col-md-2" >'
+ ' <div class="form-group">'
+ ' <label class="control-label">Description</label>'
+ '<textarea name="Description' + rowCount +'" id="Description' + rowCount +'" class="form-control descr01" cols="2" rows="2"></textarea>'
+ '</div>'
+ '</div>'
+ '<div class="col-md-1">'
+ '<div class="form-group">'
+ '<label class="control-label">Amount</label>'
+ ' <input type="text" name="Amount' + rowCount + '" id="Amount' + rowCount +'" class="form-control amt01" />'
+ '</div>'
+ '</div>'
+ '<div class="col-md-1" >'
+ '<div class="form-group">'
+ '<label class="control-label">Invoice #</label>'
+ '<input type="text" name="InvoiceNo' + rowCount + '" id="InvoiceNo' + rowCount +'" class="form-control inv01" />'
+ '</div>'
+ '</div>'
+ '<div class="col-md-2" >'
+ '<div class="form-group">'
+ '<label class="control-label">Comments</label>'
+ '<textarea name="Comments' + rowCount +'" id="Comments' + rowCount +'" class="form-control comm01" cols="1" rows="2"></textarea>'
+ ' </div></div>'
+ '<div class="col-md-2">'
+ '<div class="form-group">'
+ ' <label>Upload Invoice</label>'
+ '<input type="file" onChange="startRead2(\'' + rowCount + '\')" name="postedFile' + rowCount + '" id="postedFile' + rowCount + '" class="form-control file01" />'
+ '<input type="hidden" name="hiddenfile' + rowCount + '" id="hiddenfile' + rowCount+'"/>'
+ '</div>'
+ '</div>'
+ '<div class="col-md-2">'
+'<div class="form-group">'
+ '<input type = "button" id ="btnRemove" value="- Row" class="btn btn-danger" />'
+'</div>'
+'</div>'
+'</div>';
$('#newClaimForm').append(rowdiv);
// debugger;
//$("input[name*='TransactionDate']").css("background-color", "yellow");
// Adding these controls to Main table class
});
});
$(document).on("click", "#btnRemove", function () {
$(this).closest("div[class='row p-t-20']").remove();
});
function startRead2(id) {
var file2 = document.getElementById('postedFile'+id);
preview = id;
if (!file2.files[0]) {
return;
}
//add data type for upload validation
if ((file2.files[0].type != 'image/jpeg') && (file2.files[0].type != 'image/jpg') && (file2.files[0].type != 'image/png')) {
alert('File Type not Supported. File must be jpeg or png');
file2.value = '';
return;
}
let filex = file2.files[0];
var reader2 = new FileReader();
var reader_data2 = reader2.readAsDataURL(filex);
reader2.onload = this.addImage2;
}
function addImage2(imgsrcs) {
let hidden_bin = document.getElementById('hiddenfile'+preview);
hidden_bin.value = imgsrcs.target.result;
}
function getAllData() {
console.log('getalldata called');
var claimTitle = $('#TransactionName').val();
var claimType = $('#ClaimTypes').val();
//Transaction Details
for (var i = 1; i <= rowCount; i++) {
var trandate = $('#mdate' + i).val();
var descr = $('#Description' + i).val();
var amt = $('#Amount' + i).val();
var invno = $('#InvoiceNo'+i).val();
var comm = $('#Comments' + i).val();
var transactionDetails = {
TransactionDate: trandate,
Description: descr,
Amount: amt,
InvoiceNumber: invno,
Comments: comm,
baseFile: base64_file
}
transactionDetailVM.push(transactionDetails);
console.log(transactionDetailVM);
}
//filled model
ClaimTransactionVM = {
TransactionName: claimTitle,
ClaimType: claimType,
TransactionDetails: transactionDetailVM
};
}
$("#btnSubmit").click(function SaveReimbursements() {
//Validations will run
console.log('Save button called');
// debugger;
getAllData();
if (ClaimTransactionVM !== null) {
var FormClaims = new FormData();
FormClaims.append('currentClaim', JSON.stringify(ClaimTransactionVM));
$.ajax({
url: '/ClaimProcess/CreateClaim',
type: 'POST',
processData: false,
contentType: 'application/json',
data: FormClaims,//JSON.stringify(ClaimTransactionVM),
success: function (response) {
if (response === true) {
console.log('Success: IsSuccess True called');
swal({
title: 'success',
text: "Claim Added Successfully.",
type: "success",
confirmButtonColor: "#007AFF"
});
}
else if (response === false) {
console.log('Success: IsSuccess False called');
swal({
title: "Error!",
text: '',
type: "warning",
confirmButtonColor: "#DD6B55",
confirmButtonText: "Ok"
});
}
}
});
}
else
console.log('Model is empty.')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row p-t-20">
<div class="col-md-2">
<div class="form-group">
<label class="control-label">Transaction Date</label>
<input type="text" name="TransactionDate1" id="mdate1" class="form-control tdate01" value="" required />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="control-label">Description</label>
<textarea name="Description1" id="Description1" class="form-control descr01" cols="2" rows="2"></textarea>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="control-label">Amount</label>
<input type="text" name="Amount1" id="Amount1" class="form-control amt01" required />
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="control-label">Invoice #</label>
<input type="text" name="InvoiceNo1" id="InvoiceNo1" class="form-control inv01" required />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="control-label">Comments</label>
<textarea name="Comments1" id="Comments1" class="form-control comm01" cols="1" rows="2"></textarea>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Upload Invoice</label>
<input type="file" name="postedFile1" onChange="startRead2('1')" id="postedFile1" class="form-control file01" required />
<input type="hidden" name="hiddenfile1" id="hiddenfile1" value=""/>
</div>
</div>
<div id="newClaimForm"></div>
<div class="col-md-2">
<div class="form-group">
<br />
<input type="button" id="btnAdd" value="+ Row" class="btn btn-dark" />
</div>
</div>
</div>
<div class="form-actions m-t-40">
**<button type="button" id="btnSubmit" class="btn btn-success"> <i class="fa fa-check"></i> Save</button>**
</div>

Value of input text is empty after appending using jQuery

I am dynamically generating a form using AJAX and on the click of a button I add more input fields. But when I enter values in the input field and inspect in developer console,I don't see any value in the input text box.
Code for generating the form
$.ajax({
method: 'GET',
url: 'api/PayrollSystem/GetEmployeeSalaryAmount?AdminId=' + 1,
success: function(data) {
if (Object.keys(data).length == 0) {
$.alert({
title: 'Saved',
content: 'Account Number Saved!',
});
var row = ('<tr ><td colspan="3" text-align="center"> <b>No Registered Users</b></td></tr>');
$('.EmpTable').append(row);
} else {
$.each(data, function(index, value) {
var rows = ('<div id="form_div"><form method="post"><table class="table table-hover employee_table' + index + ' " align=center><thead><tr><td><b>Employee</td> <td><b>Amount</td></tr></thead><tbody><tr><td><b>' + value.FullName + '</b></td><td><input type="hidden" class="form-control Leavename" name="Leavename[]" value="Basic" placeholder="Enter Leave Name"> <input readonly class="form-control LeaveAmount" type="number" name="LeaveAmount[]" value=' + value.SalaryAmount + ' /><input class="form-control EmpId" type="hidden" name="Id[]" value=' + value.Id + ' /></td></tr><tr id="row' + index + 1 + '"><td><input type="text" class="form-control Leavename" name="Leavename[]" placeholder="Enter Leave Name"> </td><td> <input type="number" class="form-control LeaveAmount" name="LeaveAmount[]" placeholder="Enter Leave Amount"></td> </tr></tbody> </table> <input type="button" class="btn btn-success addRow" onclick="add_row(' + index + '); " value=" + Add More Payroll Item"></form> </div><hr />');
$('.EmpTable').append(rows);
});
}
}
});
Code for appending the row containing the new text box to the form
function add_row(index) {
$rowno = $(".employee_table tr").length;
$rowno = $rowno + 1;
$(".employee_table" + index + " tr:last").after("<tr id= 'row" + $rowno + "' > <td><input type='text' class='form-control Leavename' name='Leavename[]' placeholder='Enter Leave Name'> </td><td> <input type='number' name='LeaveAmount[]' class='form-control LeaveAmount' placeholder='Enter Leave Amount'></td><td> <input type='button' value='x' onclick=delete_row('row" + $rowno + "') ><br></td></tr>");
}
Immediate help will be well appreciated.
EDIT: My loop logic that gave no value when looping through the text boxes of each form generated.
$('#saveAdj').click(function() {
$('form').each(function() {
var thisForm = this;
alert($('.EmpId', thisForm).val());
alert($('.Leavename', thisForm).val());
alert($('.LeaveAmount', thisForm).val());
});
})

jQuery Calculations after appending more input fields

I am building an expense template an am having an issue regarding using jQuery Calculations and click functionality to append a set of input fields.
I am combining twooncodes, one to calculate the sum of the values in input fields, and the other to Add a new row of input fields when the user clicks so (these are also to be added to the sum). Problem is, the sum is not adding to the total from the newly appended rows. Only the default row of fields adds.
Any help is appreciated (Fiddle ex: http://jsfiddle.net/NicoleScotsburn/o8x02sjh/4/ )
Appending table with inputs code:
//Increment Variables
var items = $('#items');
var i = $('#items td').size() + 1;
var mileage = $('#mileage');
var j = $('#mileage td').size() + 1;
//Append Table Rows
$('#addItem').on('click', function() {
$('<tr><td> <label for="date"><input type="text" id="date" size="10" name="date_' + i +'" value="" placeholder="mm/dd/yyyy" /></label></td>' +
'<td> <label for="desc"><input type="text" id="desc" size="30" name="desc_' + i +'" /></label></td>' +
'<td> $<label for="entmt"><input type="text" id="sum" size="10" name="entmt_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="meals"><input type="text" id="sum" size="10" name="meals_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="other"><input type="text" id="sum" size="10" name="other_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="travel"><input type="text" id="sum" size="10" name="travel_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="lodging"><input type="text" id="sum" size="10" name="lodging_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="hst"><input type="text" id="sum" size="10" name="hst_' + i +'" placeholder="0.00" /></label></td>' +
'<td> Remove</td></tr>').appendTo(items);
i++;
return false;
});
$('#addMileage').on('click', function() {
$('<tr><td> <label for="mdate"><input type="text" id="mdate" size="10" name="mdate' + j +'" value="" placeholder="mm/dd/yyyy" /></label></td>' +
'<td> <label for="mlocation"><input type="text" id="mlocation" size="30" name="mlocation' + j +'" value="" placeholder="" /></label></td>' +
'<td> <label for="km"><input type="text" id="km" size="10" name="km' + j +'" value="" placeholder="" />KM</label></td>' +
'<td> Remove</td></tr>').appendTo(mileage);
j++;
return false;
});
//Remove Buttons
$('body').on('click', '#remItem', function() {
if( i > 2 ) {
$(this).parents('tr').remove();
i--;
}
return false;
});
$('body').on('click', '#remMileage', function() {
if( j > 2 ) {
$(this).parents('tr').remove();
j--;
}
return false;
});
Calculation function: (This works assuming the id of the input is id="sum" and gets outputted to another input called totalsum.
$("input[id^=sum]").sum("keyup", "#totalSum");
I am not familiar with jQuery Calculations, but it looks like what you are doing can be achieved using plain jQuery or javascript. I did a quick google search for jquery sum and I found this other stackoverflow post that might help you. stackoverflow sum
You can add a class attribute called "sum" to all the fields you want to sum up and use the jquery marked as the answer. Once you get done calculating the total you can assign it to the total amount input field.
$('.sum').blur(function () {
var sum = 0;
$('.sum').each(function() {
sum += Number($(this).val());
});
$("#totalsum").val(sum);
});​​​​​​​​​

Categories