Generate table, store values from json array - javascript

I need to create tables for each index in a given array, also i need to store those values so that my for loops sends them to the tables created.
JavaScript:
for (c=0; c < components_count.length; c++)
{
console.log(components_count[c]);
}
how can this be done?
Here is the full JS:
var index;
var data;
var parsed;
$(document).ready(function() {
$.get('policy.json', function(data){
index = data;
},"json");
});
function search(){
var movement_select = $("#movements").val();
var id = $("#idSubmit").val();
var refnr = index.refnr;
var index_movements = index.movements;
//console.log(movement_select);
//for loop to test which movement from dropdown list! Done!
for (m=0; m < index_movements.length; m++)
{
if (index_movements[m].date == movement_select)
{
movement_select = index_movements[m];
}
}
var movements = index.movements;
var movements_description = movement_select.description;
var movements_premium = movement_select.premium;
var movements_payer = movement_select.payer;
var movements_payer_id = movement_select.payer.personid;
var movements_payer_name = movement_select.payer.name;
var movements_payer_surname = movement_select.payer.surname;
var movements_payer_fullname = movements_payer_name + " " + movements_payer_surname;
var movements_owner = movement_select.owner;
var movements_owner_id = movement_select.owner.personid;
var movements_owner_name = movement_select.owner.name;
var movements_owner_surname = movement_select.owner.surname;
var movements_owner_fullname = movements_owner_name + " " + movements_owner_surname;
var components_count = movement_select.components;
for (c=0; c < components_count.length; c++)
{
console.log(components_count[c]);
}
var components = movement_select.components[0];
var components_description = movement_select.components[0].description;
var components_premium = movement_select.components[0].premium;
var components_cover = movement_select.components[0].cover;
var components_commencementdate = movement_select.components[0].commencementdate;
// table 1 --------------------------------------------------
$("#id").html(id);
$("#refnr").html(refnr);
$("#movements_payer_fullname").html(movements_payer_fullname);
$("#movements_owner_fullname").html(movements_owner_fullname);
$("#refnr").html(refnr);
// table 2 --------------------------------------------------
}
and here is the JSON:
{
"policyid":"1000",
"refnr":"gcsa000923",
"movements":
[
{
"date":"2012/06/01",
"description":"Accept",
"premium":"R30.00",
"payer":{"personid":"928374","name":"Hansie","surname":"slim"},
"owner":{"personid":"928374","name":"Hansie","surname":"slim"},
"components":
[
{
"description":"Basic cover",
"premium":"R10.00",
"cover":"R0.00",
"commencementdate":"2012/06/01"
},
{
"description":"Cancer",
"premium":"R10.00",
"cover":"R20 000.00",
"commencementdate":"2012/06/01"
}
]
},
{
"date":"2012/08/01",
"description":"Policy Alteration",
"premium":"R30.00",
"payer":{"personid":"928374","name":"Hansie","surname":"slim"},
"owner":{"personid":"928374","name":"Hansie","surname":"slim"},
"components":
[
{
"description":"Basic cover",
"premium":"R10.00",
"cover":"R0.00",
"commencementdate":"2012/06/01"
},
{
"description":"Cancer",
"premium":"R10.00",
"cover":"R20 000.00",
"commencementdate":"2012/06/01"
},
{
"description":"Disability cover",
"premium":"R20.00",
"cover":"R40 000.00",
"commencementdate":"2012/09/01"
}
]
}
]
}
Solved:
for (c=0; c < components_count.length; c++)
{
$('#append').append("Description: " + components_count[c].description + " " + '<br>');
$('#append').append("Premium: " + components_count[c].premium + " " + '<br>');
$('#append').append("Cover: " + components_count[c].cover + " " + '<br>');
$('#append').append("Commencement Date: " + components_count[c].commencementdate + " " + '<br>' + '<br>');
}
I forgot about .append ^^

Related

how dinamically variable javascript

I am a javascript beginner, I have a multiple choice exam project where I want to get response data for each selected answer. I can do it by typing the code manually but I want to make the code efficient because the data can be more than 50 questions.
heres my best code .
var i;
for (i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
window['radio' + i] = document.querySelectorAll("input[name='optionTrue" + i + "']");
window['rubahtombol' + i] = document.getElementById("buton" + i);
}
let findSe = () => {
let selected = document.querySelector("input[name='optionTrue1']:checked").value;
var soalId = document.getElementById("idSoal1").value;
var opsiPilih = document.getElementById("jawaban" + selected).textContent
document.getElementById("pilihan1").textContent = ". " + opsiPilih;
rubahtombol1.classList.remove("btn-secondary");
rubahtombol1.classList.add("btn-primary")
}
let findSe1 = () => {
let selected = document.querySelector("input[name='optionTrue2']:checked").value;
var soalId = document.getElementById("idSoal2").value;
var opsiPilih = document.getElementById("jawaban" + selected).textContent
document.getElementById("pilihan2").textContent = ". " + opsiPilih;
rubahtombol2.classList.remove("btn-secondary");
rubahtombol2.classList.add("btn-primary")
}
radio1.forEach(radioBtn => {
radioBtn.addEventListener("change", findSe1);
});
radio2.forEach(radioBtn1 => {
radioBtn1.addEventListener("change", findSe2);
});
findSe1();
findSe2();
i'm trying to do this but not working
var i;
for (i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
window['radio' + i] = document.querySelectorAll("input[name='optionTrue" + i + "']");
window['rubahtombol' + i] = document.getElementById("buton" + i);
window['findSe' + i] = () => {
let selected = document.querySelector("input[name='optionTrue1']:checked").value;
var soalId = document.getElementById("idSoal1").value;
console.log(selected);
var opsiPilih = document.getElementById("jawaban" + selected).textContent
console.log("aku pilih:" + opsiPilih);
console.log("id saol:" + soalId);
document.getElementById("pilihan1").textContent = ". " + opsiPilih;
window['rubahtombol'+i.classList.remove("btn-secondary")];
window['rubahtombol'+i.classList.add("btn-primary")];
}
}
radio1.forEach(radioBtn => {
radioBtn.addEventListener("change", findSe1);
});
radio2.forEach(radioBtn1 => {
radioBtn1.addEventListener("change", findSe2);
});
findSe1();
findSe2();
what i imagine is, i want do that in one looping
Your second approach looks pretty close, but you need to make i local to the loop body. See JavaScript closure inside loops – simple practical example
But you can make it a little cleaner with OOP.
class Button {
contructor(i) {
this.index = i;
this.radio = document.querySelectorAll(`input[name='optionTrue${i}']`);
this.rumbahtombol = document.getElementById("buton" + i);
this.radio.addEventListener("change", this.findSe.bind(this));
}
findSe() {
let selected = document.querySelector(`input[name='optionTrue${this.index}']:checked`).value;
let soalId = document.getElementById(`idSoal${this.index}`).value;
let opsiPilih = document.getElementById("jawaban" + selected).textContent;
document.getElementById(`pilihan${this.index}`).textContent = ". " + opsiPilih;
this.rubahtombol.classList.remove("btn-secondary");
this.rubahtombol.classList.add("btn-primary")
}
}
for (let i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
new Button(i);
}
i did a little change from the code made by #Barmar and it worked
class Button {
contructor(i) {
let radio = [];
this.index = i;
radio[i] = document.querySelectorAll(`input[name='optionTrue` + i + `']`);
radio[i].forEach(radioBtn => {
radioBtn.addEventListener("change", this.findSe.bind(this));
});
}
findSe() {
let rubahtombol = []
let selected = document.querySelector(`input[name='optionTrue${this.index}']:checked`).value;
let soalId = document.getElementById(`idSoal${this.index}`).value;
let opsiPilih = document.getElementById("jawaban" + selected).textContent;
document.getElementById(`pilihan${this.index}`).textContent = ". " + opsiPilih;
rubahtombol = document.getElementById(`buton${this.index}`);
rubahtombol.classList.remove("btn-secondary");
rubahtombol.classList.add("btn-primary")
}
}
for (let i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
new Button(i).contructor(i);
}

Javascript object set to another object is undefined

For my chrome extension, I have a function called storeGroup that returns an object. However, in function storeTabsInfo, when I call storeGroup and set it equal to another object, the parts inside the object are undefined. The object is being populated correctly in storeGroup, so I'm not sure why it's undefined?
function storeTabsInfo(promptUser, group)
{
var tabGroup = {};
chrome.windows.getCurrent(function(currentWindow)
{
chrome.tabs.getAllInWindow(currentWindow.id, function(tabs)
{
/* gets each tab's name and url from an array of tabs and stores them into arrays*/
var tabName = [];
var tabUrl = [];
var tabCount = 0;
for (; tabCount < tabs.length; tabCount++)
{
tabName[tabCount] = tabs[tabCount].title;
tabUrl[tabCount] = tabs[tabCount].url;
}
tabGroup = storeGroup(promptUser, group, tabName, tabUrl, tabCount); // tabGroup does not store object correctly
console.log("tabGroup: " + tabGroup.tabName); // UNDEFINED
chrome.storage.local.set(tabGroup);
})
})
}
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
var groupCountValue = group.groupCount;
var groupName = "groupName" + groupCountValue;
groupObject[groupName] = promptUser;
var tabName = "tabName" + groupCountValue;
groupObject[tabName] = name;
var tabUrl = "tabUrl" + groupCountValue;
groupObject[tabUrl] = url;
var tabCount = "tabCount" + groupCountValue;
groupObject[tabCount] = count;
var groupCount = "groupCount" + groupCountValue;
groupObject[groupCount] = groupCountValue + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject[groupName] + " " + groupObject[tabName] + " " + groupObject[tabUrl] + " " + groupObject[tabCount] + " " + groupObject[groupCount]);
return groupObject;
}
As i said in the comment above you created the groupObject dict keys with the group count so you should use it again to access them or remove it, if you want to use it again although i think this isnt necessary so use:-
... ,tabGroup[tabName + group.groupCount]...
But if you want to get it easily as you wrote just write this code instead of your code:-
function storeGroup(promptUser, group, name, url, count)
{
var groupObject = {};
// current count of group
groupObject['groupName'] = promptUser;
groupObject['tabName'] = name;
groupObject['tabUrl'] = url;
groupObject['tabCount'] = count;
groupObject['groupCount'] = group.groupCount + 1;
// successfully shows parts of groupObject
console.log("Final group: " + groupObject['groupName'] +
" " + groupObject['tabName'] + " " + groupObject['tabUrl'] +
" " + groupObject['tabCount'] + " " +
groupObject['groupCount']);
return groupObject;
}

Is there a way to have multiple inline configured ckeditors with single toolbar DOM element

An inline configured ckeditor has its toolbar attached to document body. Unless the user didn't focus the editor the toolbar is hidden. If we have multiple inline editors on same page, there will be the same number toolbar DOM elements attached to the body - each one with specific identifier. My question is, if there is a way to have a single toolbar DOM element for multiple inline ckeditors? I know (and I'm using in different context) the shared space plugin which does that, but the drawback is that one should provide an element to which the single toolabar would be attached. That's OK, but it is static and stays at the place where it's placed in the DOM order and I'd like it to be repositioned next to the currently focused editor.
Seems like I either have to use the default inline behavior or to use the shared space plugin and to reposition the single toolbar instance myself.
Any ideas on this issue or something I'm missing?
No, every CKEditor creates its own toolbar. But you can create your own plugin for this which is actually just displaying the toolbar of the active element. I have created one have a look. You do require to configure the your editor config too.
CKEDITOR.plugins.add('grouplabel', {
init : function(editor) {
function getCorrespondingName(no) {
var tempNo = 0;
for (var i = 0; i < editor.config.toolbar.length; i++) {
if (editor.config.toolbar[i].groupName != undefined) {
if (tempNo == no) {
return i;
}
tempNo++;
}
}
}
function toggleGroupDisplay(evt) {
if (evt.data.isMinimized) {
resetAllAbsolute();
$(this).find(".absoluteToolCont").toggleClass("displayNone");
} else {
$('.' + evt.data.grpID).each(function() {
toggleGroupDisplayInd(this)
});
}
}
function resetAllAbsolute() {
$(".absoluteToolCont").addClass("displayNone");
}
function toggleGroupDisplayInd(obj) {
var idM = $("#" + obj.id).parent().attr("id");
$("#" + idM + "> span").toggleClass("displayNone");
$("#" + idM).toggleClass("toggleMargin");
$("#groupLabel_" + idM).toggleClass("toggleMargin");
$("#groupLabelArrowBtn_" + idM).toggleClass("groupLabelArrowDown");
}
var openContainerArray = [ "CHARACTER", "TEXT ALIGN" ];
function createMainGroups() {
for (var j = 0; j < editor.toolbox.toolbars.length; j++) {
var grpId = editor.toolbox.toolbars[j].id;
var conNo = getCorrespondingName(j);
var isGroup = editor.config.toolbar[conNo].groupNR;
if (!isGroup) {
createMainGroup(conNo, grpId);
}
}
}
function createMainGroup(conNo, grpId) {
// console.log(conNo, grpId)
var name = editor.config.toolbar[conNo].groupName[0];
var className = editor.toolbar[conNo].name;
var name = editor.config.toolbar[conNo].groupName[0];
var elementDiv = groupLabelElementDiv(grpId, className);
var textDiv = "<div class='textGroupLabel'></div>";
var arrowDiv = "<div id='groupLabelArrowBtn_" + grpId
+ "' class='groupLabelArrowUp'></div>";
$("#" + grpId).addClass("editorGroup transitionType");
if (editor.config.showIconOnly) {
detachAndMakeAbsolute(grpId);
}
$("#" + grpId).prepend(elementDiv);
$("#groupLabel_" + grpId).append(textDiv);
if (!editor.config.showIconOnly) {
$("#groupLabel_" + grpId).append(arrowDiv);
}
addNameOrIcon(editor, name, grpId);
$(" #groupLabel_" + grpId).unbind("click").bind("click", {
grpID : "groupLabel_" + className,
isMinimized : editor.config.showIconOnly
}, toggleGroupDisplay);
var bool = false;
if (!editor.config.showIconOnly) {
for (var k = 0; k < openContainerArray.length; k++) {
if (name == openContainerArray[k]) {
bool = true;
}
}
}
showGroup(bool, grpId);
}
function detachAndMakeAbsolute(grpId) {
var divId = "absoluteToolCont_" + grpId
var absoluteDiv = "<div class='displayFlexAbsolute"
+ " absoluteToolCont' id='" + divId + "'></div>";
$("#" + grpId).prepend(absoluteDiv);
var detachedDiv = $("#" + grpId + "> span").detach();
// console.log(detachedDiv)
detachedDiv.appendTo("#" + divId);
resetAllAbsolute();
}
function showGroup(bool, grpId) {
if (!bool) {
$("#" + grpId + "> span").toggleClass("displayNone");
$("#" + grpId).toggleClass("toggleMargin");
$("#groupLabel_" + grpId).toggleClass("toggleMargin");
$("#groupLabelArrowBtn_" + grpId).toggleClass(
"groupLabelArrowDown");
}
}
function addNameOrIcon(editor, name, grpId) {
var groupName = $("#groupLabel_" + grpId + ">.textGroupLabel");
var divId = "absoluteToolCont_" + grpId
if (!editor.config.showIconOnly) {
groupName.text(name);
} else {
var clsName = name.replace(/ /g, '');
var detachedDiv = $("#" + divId).detach();
$("#groupLabel_" + grpId).prepend(detachedDiv);
groupName.html("<div class='iconToolbar " + clsName
+ "'></div>");
var overFlowRObj = "#cke_" + editor.name + " .cke_inner "
+ ".cke_top";
$(overFlowRObj).addClass("cke_top_overflow");
}
}
function groupLabelElementDiv(grpId, className) {
var elementDiv = "<div id='groupLabel_" + grpId
+ "' class='groupLabel transitionType groupLabel_"
+ className + "'></div>";
return elementDiv;
}
function createSubGroup() {
var loopVar = 0;
var divEle = '<div class="subGrpLabel textGroupLabel">' + "Font"
+ '</div>';
/*
* for (var k = 0; k < editor.toolbar.length; k++) { if
* (editor.toolbar[k] != "/") { for (var l = 0; l <
* editor.toolbar[k].items.length; l++) { if
* (editor.toolbar[k].items[l].type == "separator") { //
* console.log("sep") // $(editor.toolbar[k].items[l]).text("name"); } } } }
*/
}
editor.on('destroy', function() {
/* alert(this.name) */
var undoName = "undoRedoCont" + editor.name;
$("#" + undoName).remove();
});
editor.on('instanceReady', function() {
// console.log(previewSeen);
$("#universalPreloader").addClass("displayNone");
createMainGroups();
createSubGroup();
focusEvent();
undoRedoButtonSeprator();
});
function undoRedoButtonSeprator() {
var undoRedoContEle = "<div class='urcEle' id='undoRedoCont"
+ editor.name + "'></div>";
$("#undoRedoContSetParent").append(undoRedoContEle);
var ele = $("#" + editor.ui.instances.Undo._.id).detach();
$("#undoRedoCont" + editor.name).append(ele);
$(ele).addClass("cke_button_75px");
ele = $("#" + editor.ui.instances.Redo._.id).detach();
$("#undoRedoCont" + editor.name).append(ele);
$(ele).addClass("cke_button_75px");
$("#undoRedoCont" + editor.name).addClass("displayNone");
}
function focusEvent() {
var editorObj = /* parent. */$("#cke_wordcount_" + editor.name);
editorObj.addClass("displayFlexRelative").addClass("displayNone")
.addClass("vertical-align-middle").addClass(" flexHCenter")
.css("width", "160px");
var undoRedoCont = /* parent. */$("#undoRedoCont" + editor.name);
undoRedoCont.addClass("displayNone");
editor.on('focus', function(e) {
onFoucs(e);
});
editor.on('blur', function(e) {
onBlur(e);
});
}
function onBlur(e) {
var editorObj = /* parent. */$("#cke_wordcount_" + e.editor.name);
editorObj.addClass("displayNone");
$("#undoRedoCont" + editor.name).addClass("displayNone");
$("#dummyUNDOREDO").removeClass("displayNone");
resetAllAbsolute();
/*
* if (e.editor.config.customInline) {
* $("#toolbarEditorInline").addClass("displayNone"); }
*/
}
function onFoucs(e) {
var editorObj = /* parent. */$("#cke_wordcount_" + e.editor.name)
editorObj.removeClass("displayNone");
$("#undoRedoCont" + editor.name).removeClass("displayNone");
$("#dummyUNDOREDO").addClass("displayNone");
/*
* if (e.editor.config.customInline) {
* $("#toolbarEditorInline").removeClass("displayNone"); }
*/
}
CKEDITOR.document.appendStyleSheet(CKEDITOR.plugins
.getPath('grouplabel')
+ 'css/style.css');
}
});

How to process large jquery each loop without crashing browser(mainly firefox)

I made a javascript code to create some html element in parent iframe based on user selection from an iframe in a popup.
My code is given below.
The each loop may contain 50 to 150 iteration. Sometimes when I call function AddProcedures the Mozilla crashes during iteration, Is there any way to fix this issue or to reduce the browser load. I tried to put setTimeout after some code blocks but it didn't help.
I have also changed the for loop to jquery each, just to try if that helps.
var tot_codes = 0;
function doAddProcedure(thisVal,resolve){
var enc_id = $("#cpt_encounter").val();
var rowId = window.parent.$("[data-encounterBilled='"+ enc_id +"']").closest('tr').attr('id'); // table row ID
var recalc = parseInt(rowId.substring(rowId.indexOf('id-')+3));
var countval = $("#last_id").val();
//Load issue Fix
//Old code
//for (i = 0; i < document.cpt.elements.length; i++) {
//if (document.cpt.elements[i].type == "checkbox") {
//if (document.cpt.elements[i].checked == true) {
$('#cpt input:checkbox:checked').each(function(){
setTimeout(function() { }, 100);
var currentCodeMod = $(this).attr("data-codemod");
var currentCodeTypid = $(this).attr("data-codeTypeid");
if (currentCodeMod == null)
return;
tot_codes++;
var nextcntval = parseInt(countval) + 1;
var code_no = $(this).attr("id").replace("cpt_chkbx", "");
var Code = $("#codeVal" + code_no).val();
var just = $("#codeType" + code_no).val();
var categoryId = $("#codeType" + code_no).data("categoryid"); //Added to get category //Bug Fix
var Name = $("#cpttext" + code_no).val();
var codedisp = Code + ':' + Name;
var Modifier = '';
//if($("#modifier_setngs").val() == 1){
var Modifier1 = $("#modcpt1"+code_no).val() != '' ? $("#modcpt1"+code_no).val() + ":" : '';
var Modifier2 = $("#modcpt2"+code_no).val() != '' ? $("#modcpt2"+code_no).val() + ":" : '';
var Modifier3 = $("#modcpt3"+code_no).val() != '' ? $("#modcpt3"+code_no).val() + ":" : '';
var Modifier4 = $("#modcpt4"+code_no).val() != '' ? $("#modcpt4"+code_no).val() + ":" : '';
Modifier = Modifier1 + Modifier2 + Modifier3 + Modifier4;
//}
var codetableid = $("#code_tab_id" + code_no).val();
var j = countval; /* lineitem wise uniqid */
//var encounter = window.parent.$('#codetype-' + j).closest('tr.charge-entry-row').find('.expand-actions').attr('data-encounterid');
var encounter = enc_id;
var codeforarr = encounter + ':' + just + ':' + Code + '::' + Modifier;
window.parent.pushToArray(codeforarr);
var f = 0;
$(window.parent.$("#codetype-" + countval).parents().find('.inner-table .charge-entry-row')).each(function() {
//console.log($(this).find('.inputStringHidden').val() + '/' + codeforarr);
if ($(this).find('.inputStringHidden').val() == codeforarr) {
var exis_row_id = $(this).find('.inputStringHidden').attr('id').split('inputStringHidden-');
j = exis_row_id[1].toString();
f = 1;
$(this).find('.front_pay_codes_display').trigger('click');
}
});
if (f == 0) {
if (window.parent.document.getElementById('inputStringHidden-' + countval).value != '') {
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = parseInt(countval) + 1;
j = countval.toString();
}
window.parent.$("#add-" + countval).trigger("click");
window.parent.$("#codetype-" + (countval)).val(currentCodeTypid);
window.parent.$("#codetype-" + countval).trigger("change");
}
window.parent.document.getElementById('inputString' + j).value = codedisp;
window.parent.document.getElementById('category-' + j).value = categoryId; //Added to set category //Bug Fix
window.parent.document.getElementById('string_id' + j).value = Code;
window.parent.document.getElementById('string_value' + j).value = Name;
window.parent.document.getElementById('inputStringHidden-' + j).value = codeforarr;
window.parent.document.getElementById('codetableid-' + j).value = codetableid;
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.val-change-bit').val(1);
setTimeout(function() {}, 100);
window.parent.$("#suggestions" + j).hide();
window.parent.$("#inputString" + j).focus();
var uniqidHidden = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.uniqid-hidden').val();
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').text(Modifier);
//if($("#modifier_setngs").val() == 1){
if (f == 0) {
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').addClass('area-hide');
}else{
window.parent.$('#add-modifier' + j).parent().find('.displaymode-elem').removeClass('area-hide');
}
window.parent.$('#modifiers' + uniqidHidden).val(Modifier);
arr = Modifier.split(':');
window.parent.$('#modifier-' + uniqidHidden + '-1').val(arr[0]);
window.parent.$('#modifier-' + uniqidHidden + '-2').val(arr[1]);
window.parent.$('#modifier-' + uniqidHidden + '-3').val(arr[2]);
window.parent.$('#modifier-' + uniqidHidden + '-4').val(arr[3]);
//}
var eclaimPlanActive = window.parent.$('#eclaimPlanActive').val();
var price = $("#cpt_price" + code_no).val();
var price_level = $("#pricelevelhidden" + code_no).val();
if (price == 0 || price == null)
price = 0;
window.parent.$('#price-' + j).val(price);
window.parent.$('#bill-pricelevel-' + j).val(price_level);
/** Charge Total **/
var chargeTotal = window.parent.$('#charge-total').text().replace(/[\s\,]/g, '').trim();
if (chargeTotal == '')
chargeTotal = parseFloat(0);
var tempChargeTotal = parseFloat(chargeTotal) + parseFloat(price);
window.parent.$('#charge-total span').html(tempChargeTotal);
/** End **/
var units = $("#cpt_units" + code_no).val(); //data[0]['units']
if (units == 0 || units == null)
units = 1;
window.parent.$('#qty-' + j).val(units);
var tax = 0;
var disc = 0;
setTimeout(function() { }, 100);
if (window.parent.$('#tax-' + j).length > 0)
tax = window.parent.$('#tax-' + j).val().replace(/[\s\,]/g, '');
if (window.parent.$('#discount-' + j).length > 0)
disc = window.parent.$('#discount-' + j).val().replace(/[\s\,]/g, '');
var amount = price * units;
amount = amount + ((amount * tax) / 100);
if (disc > 0) {
var p = price * units;
var dc = ((p * disc) / 100);
amount = amount - dc;
}
/** Discount Total **/
var disTotal = window.parent.$('#discount-total').text().replace(/[\s\,]/g, '').trim();
if (disTotal == '')
disTotal = parseFloat(0);
var tempDisTotal = parseFloat(disTotal) + parseFloat(dc);
if (isNaN(tempDisTotal) == true) {
tempDisTotal = '0.00';
}
window.parent.$('#discount-total').html(tempDisTotal);
/** End **/
if (!parseFloat(window.parent.$('#lineitempaid-' + j).val()))
window.parent.$('#lineitempaid-' + j).val('0.00');
window.parent.$('#total-' + j).val(amount);
window.parent.$('#remainder-' + j).val(amount);
window.parent.$('#hidremainder-' + j).val(amount);
//insurance and patient_share
if (eclaimPlanActive == '1') {
var codetableid = window.parent.$('#codetableid-' + j).val();
var parentRowVal = parseInt(window.parent.$('#codetableid-' + j).closest('tr').find('.row_value').attr('data-rowvalue')) - 1;
var insData1 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata1');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData1);
if (window.parent.$('#have-benefit').val() == '0') {
var insData2 = window.parent.$('tr#row-id-' + parentRowVal + ' .encounter').attr('data-insdata2');
window.parent.getBenefitCategoryOfCode(j, codetableid, insData2);
}
}
var passParams = '';
window.parent.calculate('qty-' + j, passParams);
//Updating the title
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.fi-searchitems').attr('data-original-title', codedisp);
if (f == 0) {
//Display DIv :: Relace with new values
var cloneLabel = window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').clone();
//In Edit Mode
if (cloneLabel.find('.displaymode-elem').length > 0) {
var $max_length = 16;
var trucncateCode = Name;
if (trucncateCode.length > $max_length)
trucncateCode = trucncateCode.substring(0, $max_length) + '...';
cloneLabel.find('.front_pay_codetype').text(just + ":");
cloneLabel.find('.front_pay_code').text(trucncateCode);
cloneLabel.find('.displaymode-elem').removeClass('area-hide');
cloneLabel.removeClass('area-hide');
cloneLabel.find("input[name='code_type']").val(just).attr('id', 'code_type-' + j);
cloneLabel.find("input[name='string_id']").val(Code).attr('id', 'string_id-' + j);
cloneLabel.find("input[name='string_value']").val(Name);
var dataType = $("#inputString" + j).closest('tr.charge-entry-row').find('.data_type').val();
if (dataType == "lab") {
var lab = $("select[name='lab_type']").find('option:selected').val();
if (cloneLabel.find("input[name='lab_type']").length > 0) {
cloneLabel.find("input[name='lab_type']").val(lab);
} else {
cloneLabel.append('<input type="hidden" name="lab_type" class="lab_type" value="' + lab + '">');
}
} else {
cloneLabel.find("input[name='lab_type']").remove();
}
setTimeout(function() { }, 100);
//Making the view
cloneLabel.removeClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.front_pay_codes_editelem').removeClass('area-show').addClass('area-hide');
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_label').replaceWith(cloneLabel);
window.parent.$("#inputString" + j).closest('tr.charge-entry-row').find('.show_autosuggest').html('');
}
window.parent.$("#codetype-" + countval).children().parent().parent().parent().siblings().find('.addnew-row').attr('data-rowadd', 'fromdb').trigger("click");
countval = nextcntval.toString();
}
else {
window.parent.$("#suggestions" + j).hide();
countval = countval.toString();
}
setTimeout(function() { }, 150);
});
window.parent.reCalculatePlanEncounterWise(recalc);
resolve("Success!");
}
function doAddPromise(thisVal){
return new Promise(function(resolve){
doAddProcedure(thisVal,resolve);
});
}
function AddProcedures(thisval)
{
$('#procedureSaveButton').text('Processing....');
// $('.fa-spinner').removeClass('hide');
top.ShowAjaxLoader('Loading..');
setTimeout(function(){
}, 2000);
//top.ShowAjaxLoader('Loading..');
setTimeout(function(){
$.when(doAddPromise(thisval)).done(function(){
if (tot_codes > 0) {
window.parent.phFrntpayClosePopup();
top.notification('Successfully added the procedures.');
//top.HideAjaxLoader('Loading..');
top.HideAjaxLoader();
$('body').removeClass('modal-open');
} else {
top.notification('Please select atleast one procedure.');
$('#procedureSaveButton').text('Add Procedures');
//$('.fa-spinner').addClass('hide');
top.HideAjaxLoader();
}
});
}, 10);
}

Multiple Group By using two look-up columns which have multi valued selection enabled on an SP 2013 list using JavaScript

So I'm working on SP 2013 and have a document library which has three Lookup columns viz : Business Unit, Axis Product and Policy form. What I'm trying to do is I have managed to group by the List items first by Business Unit column and then by the Axis Product Column. This works fine but recently I'm trying to show the count of the number of items inside a particular Axis Product. Which would be like - Axis Product : "Some Value" (Count).
I'm able to show this count with Business Unit, but not able to do this with Axis Product. So I tried querying the library with both Business Unit and Axis Product to get the count for Axis Product, I'm not sure about this approach and currently I'm getting an error message:
'collListItemAxisProduct' is undefined.
Any help would be appreciated as I've been stuck on this for a long time now. Here is my code below :
// JavaScript source code
$(function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', oGroupBy.GetDataFromList);
});
function GroupBy()
{
this.clientContext = "";
this.SiteUrl = "/sites/insurance/products";
this.lookUpLIst = "AxisBusinessUnit";
this.AxisProductlookUpList = "AXIS Product";
this.lookUpItems = [];
this.lookUpColumnName = "Title";
this.AxisProductlookupItems = [];
this.AProducts = [];
this.index = 0;
this.secondindex = 0;
this.parentList = "AXIS Rules Library";
this.html = "<div id='accordion'><table cellspacing='35' width='100%'><tr><td width='8%'>Edit</td><td width='13%'>Name</td><td width='13%'>Modified</td><td width='13%'>Underwriting Comments</td><td width='13%'>Policy Form Applicability</td><td width='13%'>AXIS Product</td><td width='13%'>Business Unit</td></tr>";
}
function MultipleGroupBy()
{
this.AxProducts = [];
this.SecondaryGroupBy = [];
this.count = "";
this.BusinessUnit = "";
this.html = "";
}
function UI()
{
this.id = "";
this.name = "";
this.modified = "";
this.acturialComments = "";
this.underWritingComments = "";
this.policyFormApplicability = [];
this.axisProduct = [];
this.businessUnit = [];
this.itemcheck = "";
this.Count = 0;
this.header = "";
this.AxisProductCount = 0;
this.trID = "";
this.SecondaryID = "";
this.LandingUrl = "&Source=http%3A%2F%2Fecm%2Ddev%2Fsites%2FInsurance%2FProducts%2FAXIS%2520Rules%2520Library%2FForms%2FGroupBy%2Easpx";
}
var oUI = new UI();
var oGroupBy = new GroupBy();
var oMultipleGroupBy = new MultipleGroupBy();
GroupBy.prototype.GetDataFromList = function () {
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.lookUpLIst);
var APList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.AxisProductlookUpList);
var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);
var secondcamlQuery = new SP.CamlQuery();
this.secondListItem = APList.getItems(secondcamlQuery);
oGroupBy.clientContext.load(collListItem);
oGroupBy.clientContext.load(secondListItem);
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.BindDataFromlookUpList), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.BindDataFromlookUpList = function (seneder,args) {
var listenumerator = collListItem.getEnumerator();
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
oGroupBy.lookUpItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
GroupBy.prototype.GetDataFromParent = function(lookUpItems)
{
var oList1 = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Business_x0020_Unit\'/>' +
'<Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq></Where></Query></View>');
this.collListItem1 = oList1.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItem1, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.CreateHTMLGroupBy), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.CreateHTMLGroupBy = function (sender,args)
{
var listenumerator = this.collListItem1.getEnumerator();
var axisproductlistenumarator = secondListItem.getEnumerator();
while (axisproductlistenumarator.moveNext()) {
var currentitem = axisproductlistenumarator.get_current(); oGroupBy.AxisProductlookupItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oUI.Count = this.collListItem1.get_count();
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oUI.trID = oGroupBy.lookUpItems[oGroupBy.index];
oMultipleGroupBy.BusinessUnit = oGroupBy.lookUpItems[oGroupBy.index];
oGroupBy.html = oGroupBy.html + "<table style='cursor:pointer' id='" + oUI.trID.replace(" ", "") + "' onclick='javascript:oUI.Slider(this.id)'><tr><td colspan='7'><h2 style='width:1100px;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>Business Unit : " + oGroupBy.lookUpItems[oGroupBy.index] + " " + "<span> (" + oUI.Count + ")</span></h2></td></tr></table>";
}
oUI.businessUnit.length = 0;
oMultipleGroupBy.SecondaryGroupBy.length = 0;
oMultipleGroupBy.SecondaryGroupBy.push(oUI.trID);
oMultipleGroupBy.html = "";
if (oUI.Count > 0) {
if (listenumerator != undefined) {
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
if (currentitem != undefined) {
oUI.id = currentitem.get_item("ID");
oUI.name = currentitem.get_item("FileLeafRef");
oUI.modified = currentitem.get_item("ModifiedDate");
//oUI.policyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
oUI.underWritingComments = currentitem.get_item("Underwriting_x0020_Comments");
//oUI.axisProduct = currentitem.get_item("AXIS_x0020_Product");
var lookupPolicyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
var lookupField = currentitem.get_item("Business_x0020_Unit");
var lookupAxisProduct = currentitem.get_item("AXIS_x0020_Product");
oUI.businessUnit.length = 0;
for (var i = 0; i < lookupField.length; i++) { oUI.businessUnit.push(lookupField[i].get_lookupValue());
}
oUI.axisProduct.length = 0;
for (var m = 0; m < lookupAxisProduct.length; m++) { oUI.axisProduct.push(lookupAxisProduct[m].get_lookupValue());
}
oUI.policyFormApplicability.length = 0;
for (var a = 0; a < lookupPolicyFormApplicability.length; a++)
{
oUI.policyFormApplicability.push(lookupPolicyFormApplicability[a].get_lookupValue());
}
oGroupBy.CreateUI(oUI);
}
}
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oGroupBy.html = oGroupBy.html + oMultipleGroupBy.html;
}
}
}
oGroupBy.index = oGroupBy.index + 1;
if (oGroupBy.index <= oGroupBy.lookUpItems.length) {
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
if(oGroupBy.index == oGroupBy.lookUpItems.length + 1)
{
oGroupBy.html = oGroupBy.html + "</table></div>";
$("#contentBox").append(oGroupBy.html);
$(".hide,.sd-hide").hide();
}
}
UI.prototype.Slider = function (id) {
$("#MSOZoneCell_WebPartWPQ3").click();
//$(".hide").hide();
var elements = document.querySelectorAll('[data-show="' + id + '"]');
$(elements).slideToggle();
}
UI.prototype.SecondarySlider = function (id) {
var elements = document.querySelectorAll('[data-secondary="' + id + '"]');
$(elements).slideToggle();
}
GroupBy.prototype.CreateUI = function (oUI) {
var BusinessUnit = "";
var AxisProduct = "";
var Policyformapplicability = "";
var tempBUnit = "";
for (var i = 0; i < oUI.businessUnit.length; i++) {
BusinessUnit = BusinessUnit + oUI.businessUnit[i] + ",";
}
for (var m = 0; m < oUI.axisProduct.length; m++) {
AxisProduct = AxisProduct + oUI.axisProduct[m] + ",";
}
for (var a = 0; a < oUI.policyFormApplicability.length; a++) {
Policyformapplicability = Policyformapplicability + oUI.policyFormApplicability[a] + ",";
}
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList1SecondGroupBy = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Business_x0020_Unit\' /><Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq>' +
'<Eq><FieldRef Name=\'AXIS_x0020_Product\' /><Value Type=\'LookupMulti\'>' + oGroupBy.AxisProductlookupItems[oGroupBy.secondindex] + '</Value></Eq></And></Where><OrderBy><FieldRef Name=\'Title\' Ascending=\'True\' /></OrderBy></Query><View>');
this.collListItemAxisProduct = oList1SecondGroupBy.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItemAxisProduct, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
if (collListItemAxisProduct != undefined) {
//oGroupBy.clientContext.load(collListItemAxisProduct);
var AxisProductlistenumerator = this.collListItemAxisProduct.getEnumerator();
if (AxisProductlistenumerator != undefined) {
oUI.AxisProductCount = this.collListItemAxisProduct.get_count();
oGroupBy.AProducts.length = 0;
if (AxisProduct != "") {
oGroupBy.AProducts = AxisProduct.split(',');
}
oGroupBy.AProducts.splice(oGroupBy.AProducts.length - 1, 1);
//alert(oGroupBy.AProducts.length);
var link = "/sites/Insurance/Products/AXIS%20Rules%20Library/Forms/EditForm.aspx?ID=" + oUI.id + oUI.LandingUrl;
var editicon = "/sites/insurance/products/_layouts/15/images/edititem.gif?rev=23";
for (var i = 0; i < oGroupBy.AProducts.length; i++) {
var SecondaryGBTableID = "";
if (oGroupBy.AProducts[i].replace(" ", "") != "") {
SecondaryGBTableID = oGroupBy.AProducts[i].replace(/\s/g, "") + oMultipleGroupBy.BusinessUnit.replace(/\s/g, "");
SecondaryGBTableID = SecondaryGBTableID.replace("&", "");
var isPresent = $.inArray(oGroupBy.AProducts[i].replace(/\s/g, ""), oMultipleGroupBy.SecondaryGroupBy);
}
oUI.SecondaryID = oUI.trID.replace("/\s/g", "") + oGroupBy.AProducts[i].replace("/\s/g", "");
if ((isPresent <= -1)) {
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr style='margin-left:10px;margin-bottom:1px solid grey;' cellspacing='36'><td ><h3 class='hide' onclick='javascript:oUI.SecondarySlider(this.id);' id='" + oUI.SecondaryID + "' data-show='" + oUI.trID.replace(" ", "") + "' style='cursor:pointer;width:100%;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>    -    AXIS Product : " + oGroupBy.AProducts[i] + " " + "<span> (" + oUI.AxisProductCount + ")</span></h3></td></tr>";
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr><td><table class='hide' data-show='" + oUI.trID.replace(" ", "") + "' width='100%' cellspacing='36' id='" + SecondaryGBTableID + "'><tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr></table></td></tr>";
}
else {
if ($("#" + SecondaryGBTableID).html() != undefined) {
$("#" + SecondaryGBTableID).append("<tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr>");
oMultipleGroupBy.html = $("#divMultiplegroupBy").html();
}
}
document.getElementById("divMultiplegroupBy").innerHTML = oMultipleGroupBy.html;
if ((isPresent <= -1) && (oGroupBy.AProducts[i] != "")) {
oMultipleGroupBy.SecondaryGroupBy.push(oGroupBy.AProducts[i].replace(/\s/g, ""));
}
}
}
}
else {
oGroupBy.secondindex = oGroupBy.secondindex + 1;
oGroupBy.CreateUI(oUI);
}
}
GroupBy.prototype.onError = function (sender, args) {
alert('Error: ' + args.get_message() + '\n');
}
// JavaScript source code
You have to call clientContext.executeQueryAsync after calling clientContext.load in order to populate any results from the SharePoint object model.
executeQueryAsync takes two parameters: first the function to execute on success, and second the function to execute if an error is encountered. Any code that depends on successfully loading values from the query should be placed in the on success function.

Categories

Resources