How to get size of array inside an json object - javascript

this is my json object
I need to get length of itemDetails array object,
I'm using
for (var i = 0; i < data[0].itemDetails.length; i++) {
itmCode = "it001";
itmName = "soap";
Qty = "4";
//netAmt = parseFloat(data[i].Net_Amt).toFixed(2);
//paidAmt = parseFloat(data[i].Paid_Amt).toFixed(2);
//balance = (parseFloat(netAmt) - parseFloat(paidAmt)).toFixed(2); //id = "damt['+i+']"
$("#invoiceDetailTbl tbody").append("<tr id=" + i + ">" + "<td>" + itmCode + "</td>" + "<td>" + itmName + "</td>" + "<td>" + Qty + "</td>" + "</tr>");
noOfItems = parseInt(noOfItems) + parseInt(Qty);
noOfProducts = parseInt(noOfProducts) + 1;
}
but always get 0 as length

Related

How to bring my first column to my automate email in App Scripts?

Some weeks ago I developed a code that takes some information from a spreadsheet each time a user submit a form, and then, send me an email with the information completed. It works really well.
However, I am intending to add a Ticket number in the first column of the sheet (without adding it in the google form) but it is not being recognized by my code.
Do you have any clue about how could I add this first column to my email each time I receive a new submit?
I attach my code.
function formSubmitReply(e) {
// VARIABLES
var ticketNo;
var alUser = e.values[1];
var country = e.values[3];
var language = e.values[2];
var category = e.values[4];
var title = e.values[5];
var questions = e.values[6];
var attach = e.values[7];
var entityEn = e.values[8];
var categoryEn = e.values[9];
var titleEn = e.values[10];
var questionsEn = e.values[11];
var attachEn = e.values[12];
var userEmail = "nam.hr#airliquide.com";
var msgFr =
// Add table style and format the cells with th and tr
"<table border='1' border-radius='5px' style='border-collapse:collapse; font-family:sans-serif;'>" +
"<tr>" +
"<th>Employé AL</th>" +
"<th>Sélection du pays</th>" +
"<th>Langue préférée</th>" +
"<th>Catégorie</th>" +
"<th>Sujet</th>" +
"<th>Contenu de la demande</th>" +
"<th>Pièce jointe</th>" +
"<th>#</th>" +
"</tr>" +
"<tr>" +
"<td>" + alUser + "</td>" +
"<td>" + country + "</td>" +
"<td>" + language + "</td>" +
"<td>" + category + "</td>" +
"<td>" + title + "</td>" +
"<td>" + questions + "</td>" +
"<td>" + attach + "</td>" +
"<td>" + ticketNo + "</td>" +
"</tr>" +
"</table>";
var msgEn =
// Add table style and format the cells with th and tr
"<table border='1' style='border-collapse:collapse; font-family:sans-serif;'>" +
"<tr>" +
"<th>AL user</th>" +
"<th>Country</th>" +
"<th>Preferred Language</th>" +
"<th>Category</th>" +
"<th>Title</th>" +
"<th>Question</th>" +
"<th>Attachments</th>" +
"<th>#</th>" +
"</tr>" +
"<tr>" +
"<td>" + alUser + "</td>" +
"<td>" + entityEn + "</td>" +
"<td>" + language + "</td>" +
"<td>" + categoryEn + "</td>" +
"<td>" + titleEn + "</td>" +
"<td>" + questionsEn + "</td>" +
"<td>" + attachEn + "</td>" +
"<td>" + ticketNo + "</td>" +
"</tr>" +
"</table>";
MailApp.sendEmail({
to: userEmail,
subject: 'NAM HR Mailbox | ' + categoryEn + category,
htmlBody: (language=="English") ? msgEn : msgFr,
name: alUser,
replyTo: alUser
});
}
Solution:
You need to add the first column manually in the spreadsheet then add this code to fill up the values every form submit:
function formSubmitReply(e) {
var ss = SpreadsheetApp.getActive();
var id = e.range.getRow();
var startNum = 850; // to start the entries from T0850
var control = startNum + id - 2;
var ticketNo = "T"+control.toString().padStart(4,"0");
ss.getActiveSheet().getRange(id,1).setValue(ticketNo);
// VARIABLES
var alUser = e.values[1];
var country = e.values[3];
.....
The rest of the code should be the same as with your question.
Sample Output:

JavaScript use loop for a complex json

I am using json.data.schedules[0].liveVideoList , json.data.schedules[1].liveVideoList
, json.data.schedules[2].liveVideoList and so on
Please tell me how can I use loop here to get all path
script.js code
var b = location.search.split('b=')[1];
$.get(
"index2.php",
{ "b": b },
function (data) {
var json = JSON.parse(data);
$.each(json.data.schedules[0].liveVideoList, function (i, v) {
var str = v.thumbnailUrl.split("vi/").pop();
var datee = v.publishDate.slice(0, 9);
var timee = v.publishDate.slice(9, 20);
var tblRows = "<tr>" + "<td>" + v.title + "</td>" + "<td>" + 0 + ' ₹' + "</td>" + "<td>" + datee + "</td>" + "<td>" + timee + "</td>" + "<td><a target='_blank' href='" + str + "'>" + "WATCH/DOWNLOAD" + "</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata");
});
}
);
You can use two loops like this.
$.each(json.data.schedules, function (index, schedule) {
$.each(schedule.liveVideoList, function (i, v) {
var str = v.thumbnailUrl.split("vi/").pop();
var datee = v.publishDate.slice(0, 9);
var timee = v.publishDate.slice(9, 20);
var tblRows = "<tr>" + "<td>" + v.title + "</td>" + "<td>" + 0 + ' ₹' + "</td>" + "<td>" + datee + "</td>" + "<td>" + timee + "</td>" + "<td><a target='_blank' href='" + str + "'>" + "WATCH/DOWNLOAD" + "</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata");
});
});
A for..of loop
for (let schedule of json.data.schedules) {
//Do something with schedule
}
A for..in loop
for (let scheduleIndex in json.data.schedules) {
//Do something with json.data.schedules[scheduleIndex]
}
A for loop
for (let index = 0; index < json.data.schedules.length; index++) {
//Do something with json.data.schedules[index]
}
A while loop
var index = 0;
while (index < json.data.schedules.length) {
//Do something with json.data.schedules[index]
index++;
}

I want to fix the code concisely

var template is used as redundant I want to know how to fix it so you can use this section only once
function pluscal(data) {
var idx = index++
var form = parseInt($("#plusstr1").val()) + $("#plus_op").text() + parseInt($("#plusstr2").val())
var cal = parseInt($("#plusstr1").val()) + parseInt($("#plusstr2").val())
var template = "<tr>" +
"<td>" + idx + "</td>" +
"<td>" + form + "</td>" +
"<td>" + data.result + "</td>" +
"<td><button class='ul icon button' id='remove_btn'><i class='trash alternate icon'></i></button></td>" +
"</tr>"
$("tbody").append(template)
}
and
function minuscal(data) {
var idx = index++
var form = parseInt($("#minusstr1").val()) + $("#minus_op").text() + parseInt($("#minusstr2").val())
var cal = parseInt($("#minusstr1").val()) - parseInt($("#minusstr2").val())
var template = "<tr>" +
"<td>" + idx + "</td>" +
"<td>" + form + "</td>" +
"<td>" + data.result + "</td>" +
"<td><button class='ul icon button' id='remove_btn'><i class='trash alternate icon'></i></button></td>" +
"</tr>"
$("tbody").append(template)
}
Simply separate the logic related to template. Here I have organized it in one function. And I have merged pluscal and minuscal function.
function cal(data, calType) {
// calType need to be either plus or minus
var idx = index++
var form = parseInt($(`#${calType}str1`).val()) + $(`#${calType}_op`).text() + parseInt($(`#${calType}str2`).val())
var cal = parseInt($(`#${calType}str1`).val()) + parseInt($(`#${calType}str2`).val())
generateTemplate(idx, form, cal, data);
}
function generateTemplate(idx, form, cal, data) {
var template = `<tr>
<td> ${idx} </td>
<td> ${form} </td>
<td> ${data.result} </td>
<td><button class='ul icon button' id='remove_btn'><i class='trash alternate icon'></i></button></td>
</tr>`
$("tbody").append(template)
}
Create another function what returns the template
function getTemplate(idx, form, result) {
return "<tr>" +
"<td>" + idx + "</td>" +
"<td>" + form + "</td>" +
"<td>" + result + "</td>" +
"<td><button class='ul icon button' id='remove_btn'><i class='trash alternate icon'></i></button></td>" +
"</tr>";
}
So then you can use like this
function pluscal(data) {
var idx = index++
var form = parseInt($("#plusstr1").val()) + $("#plus_op").text() + parseInt($("#plusstr2").val())
var cal = parseInt($("#plusstr1").val()) + parseInt($("#plusstr2").val())
var template = getTemplate(idx, form, data.result);
$("tbody").append(template)
}
try this
function multiCase(caseType, data) {
if (caseType === 'Maj') {
str1 = "#plusstr1",
str2 = "#plusstr2",
op = "#plus_op"
} else {
str1 = "#minusstr1",
str2 = "#minusstr2",
op = "#minus_op"
}
var idx = index++
var form = parseInt($(str1).val()) + $(op).text() + parseInt($(str2).val())
var cal = parseInt($(str1).val()) + parseInt($(str2).val())
/* And other part of your function
...
...
*/
Hope it helps

one ajax loop with 2 outputs error innerHTML

Having a few issues trying to get this function output to an ajax table (working fine) and an input box called connectsList1.
i cannot get it to spit out into the input box without error, the error is
Uncaught TypeError: Cannot set property 'innerHTML' of null
and
connectsList1 is not defined
function getConnections(txt1) {
func_getConnections(
function (response) {
var sortorder = txt1;
var arr = response;
var i;
var Count;
var mCount;
var oCount;
var out =
"<thead>"
for (i = 0; i < arr.length; i++) {
out +=
"<tr>" +
"<tbody>" +
"<tr class=\"" + ReturnValuesAsColor(arr[i].o, arr[i].m, arr[i].server_proc) + "\">" +
"<td>" + arr[i].id + "</td>" +
//"<td>" + arr[i].user_id + "</td>" +
"<td>" + arr[i].user_name + "</td>" +
"<td>" + arr[i].workstation_name + "</td>" +
"<td>" + (!!arr[i].ip_address ? arr[i].ip_address : '') + "</td>" +
"<td>" + formatDateTime(arr[i].connect_date, 'datelongtime') + "</td>" +
"<td>" + formatDateTime(arr[i].refresh_date, 'datelongtime') + "</td>" +
"<td>" + (!!arr[i].app_ver ? arr[i].app_ver : '') + "</td>" +
"<td>" + (!!arr[i].app_date ? formatDateTime(arr[i].app_date, 'shortdate') : '') + "</td>" +
"<td>" + Messages_flag(arr[i].get_messages_flag) + "</td>" +
"<td>" + FixNumbers(arr[i].message_type_flags) + "</td>" +
//"<td>" + arr[i].o + "</td>" +
//"<td>" + arr[i].m + "</td>" +
"<td>" + arr[i].group_name + "</td>" +
//"<td>" + arr[i].server_proc + "</td>" +
"<td> <button id=\"DelImg1\" type=\"button\" name=\"btnsubmit\" class=\"ui-button ui-widget ui-state-default ui-corner-all\" onclick=\"clearText('<%= result.ClientID%>'); CopyId(" + arr[i].id + "); return Message(" + arr[i].id + ")\" >Delete</button> </td>" +
"</tr>" +
"</tbody>";
mCount = 0
if (arr[i].m != 0) {
mCount += 1;
} else if (arr[i].o != 0) {
oCount += +1;
} else if (arr[i].o == 0 & arr[i].m == 0) {
Count += 1;
}
document.getElementById("dtBody1").innerHTML = out;
document.getElementById('ConnectsList1').innerHTML = out;
ConnectsList1 = " Connection list: " & Count + oCount + mCount & " connection(s) Main Application : " & Count & " Online : " & oCount & " Mobile : " & mCount;
}})};
Any help or advice welcome, still learning ajax myself
document.getElementById("dtBody1") can not find any tag with id dtBody1. Make sure your HTML has an element with that ID.
And remember to declare the ConnectsList1 variable to avoid the second error.

Unknown error when calling Array.length

first of all i need to say that i don't have much experience with JS. currently i'm trying to implement an web application with MVC framework. I'm in a work to develop an app that is also compatible with Internet explorer. in that case i'm using following JS method to populate a table which is working fine with all the browsers....
function populateTable(array) {
document.getElementById("instalationTable").style.display = "block";
var table = document.getElementById("ActivityDescription_installationID");
table.innerHTML = "";
elementsInTable = array;
var x = 0;
for (i = 0; i < (array.length * 2) ; i++) {
//alert(i);
if ((i % 2) == 0) {
//ID Row
var row = table.insertRow(i);
var cell_1 = row.insertCell(0);
cell_1.innerHTML = "<input type='text' disable='' class='form-control' value=" + array[x] + ">";
x = x + 1;
var cell_2 = row.insertCell(1);
cell_2.innerHTML = "<span class='btn btn-default' onclick='showEditRow(this)'><img src='../../Content/images/1414409386_48-24.png' /></span>";
var cell_3 = row.insertCell(2);
cell_3.innerHTML = "<span class='btn btn-default' onclick='removeRow(this)'>X</apan>";
}
else {
//Detail Row
var rowDetails = table.insertRow(i);
var cell = rowDetails.insertCell(0);
//cell.colspan = "3";
cell.innerHTML = "<table style='background-color:rgb(98, 98, 98);color:black;border- radius: 5px;' margin:2%; >" +
"<tr>" +
"<td><input type='checkbox' id='"+x+"_appServer'/> Application Server</span></td>" +
"<td>" +
"<select id='" + x + "_appServerVersion'>" +
"<option>Application version</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='2'><input type='radio' name='database' id='"+x+"_emptyDb' onChange='enableOptions(1)'/>" +
" Empty Database</br><input type='radio' name='database' id='" + x + "_instalationSlt' onChange='enableOptions(2)'/> Something Databse</td>" +
"</tr>" +
"<tr id='emptyDB'>" +
"<td>" +
"Oracle Version"+
"<select id='JS_OraVersion' name='" + x + "_oraVersion' style='width:100%'>" +
"<option>Ora version</option>" +
"</select>" +
"</td>" +
"<td>" +
"Character Set" +
"<select id='JS_ChaSet' name='" + x + "_ChaSet' style='width:100%'>" +
"<option>Cha Set</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr id='dbImport'>" +
"<td>" +
"Something version" +
"<select id='JS_ImportVersion' name='" + x + "_ImportVersion' style='width:100%'>" +
"<option>Something version</option>" +
"</select>" +
"</td>" +
"<td>" +
"Something Charachter" +
"<select id='JS_ImportChaSet' name='" + x + "_ImportChaSet' style='width:100%'>" +
"<option>Something Cha</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='2'>" +
"Additional Requests </br>" +
"<textarea rows='4' id='" + x + "_specialReq' cols='37'> </textarea>" +
"<td/>"+
"</tr>"+
"</table>";
rowDetails.style.display = 'none';
Lock();
}
}
document.getElementById("instalationTable").style.display = "block";
}
i'm populating a form on the above table row, that collects some data to continue. to collect data i'm using following function which works fine with Google chrome but not with Internet explorer..
function getAllData() {
var StringtoSent = "";
for (i = 0; i < (elementsInTable.length) ; i++) {
var InsId = elementsInTable[i];
var _appServer = document.getElementById((i + 1) + "_appServer").checked;
var _appServerVersionDropDown = document.getElementById((i + 1) + "_appServerVersion");
var _appServerVersion = _appServerVersionDropDown.options[_appServerVersionDropDown.selectedIndex].value;
var _emptyDb = document.getElementById((i + 1) + "_emptyDb").checked;
var _instalationSlt = document.getElementById((i + 1) + "_instalationSlt").checked;
var _oraVersionDropDown = document.getElementsByName((i + 1) + "_oraVersion")[0];
var _oraVersion = _oraVersionDropDown.options[_oraVersionDropDown.selectedIndex].value;
var _ChaSetDropDown = document.getElementsByName((i + 1) + "_ChaSet")[0];
var _ChaSet = _ChaSetDropDown.options[_ChaSetDropDown.selectedIndex].value;
var _ImportVersionDropDown = document.getElementsByName((i + 1) + "_ImportVersion")[0];
var _ImportVersion = _ImportVersionDropDown.options[_ImportVersionDropDown.selectedIndex].value;
var _ImportChaSetDropDown = document.getElementsByName((i + 1) + "_ImportChaSet")[0];
var _ImportChaSet = _ImportChaSetDropDown.options[_ImportChaSetDropDown.selectedIndex].value;
var _specialReq = document.getElementById((i + 1) + "_specialReq").value;
StringtoSent = StringtoSent + "," + InsId + "," + _appServer + "," + _appServerVersion + "," + _emptyDb + "," + _instalationSlt + "," + _oraVersion + "," + _ChaSet + "," + _ImportVersion + "," + _ImportChaSet + "," + _specialReq + "|";
//return StringtoSent;
document.getElementById("ActivityDescription_instalationDetails").value = StringtoSent;
}
}
following image shows the error that im getting when it is ruining on VS 2012s IIS Express.
for (i = 0; i < (elementsInTable.length) ; i++) {
is the place that indicates as the error place . it always highlight the "elementsInTable.length" code segment.
Actually this error message elaborate nothing. i found some articles about the same error but occurring when trying to change the inner HTML of an element. but those solutions are not compatible for this situation.. Please help me with the problem
thanks in advance
Finally i found the Error
cell.innerHTML = "<table style='background-color:rgb(98, 98, 98);color:black;border- radius: 5px;' margin:2%; >" +
in above line i mistakenly added a CSS attribute "margin:2%;" in to a wrong place. Google chrome is intelligence enough to manage the situation and proceed the activity but Internet Explorer is not. as i found, this is the fact that prompt same error in different situations.
EG:
http://www.webdeveloper.com/forum/showthread.php?22946-innerHTML-amp-IE-Unknown-Runtime-Error
http://www.webdeveloper.com/forum/showthread.php?22946-innerHTML-amp-IE-Unknown-Runtime-Error
So if you got any unknown error in your Java Script code which uses "element.InnerHTML" or "document.Write" its better to check whether your tags are properly closed.
and i found several other situations that is generating same error
IE shows run time error for innerHTML
InnerHTML issue in IE8 and below
most of the times you can avoid this error by following W3C tag recommendations (http://www.w3.org/TR/html401/struct/global.html).

Categories

Resources