maintaining a sorted jQuery accordion - javascript

I have a situation where I receive certain events over time that each have a timestamp associated with them. I am putting it into a Jquery accordion section that is labelled by date. It works except that I wish to maintain the accordion sections in sorted descending order, i.e most recent date at the top and events belonging to that date go into that section. Here is the complete code I have so far, currently I just append a new date to the end. How do I insert so that it is sorted?
$(function() {
$("#accordion").accordion({
collapsible: true
});
});
function getRandInt(max) {
return Math.floor(Math.random() * Math.floor(max))
}
function getRandomTime() {
var t = ['AM', 'PM']
var hr = getRandInt(13);
var mn = getRandInt(60);
var sec = getRandInt(60);
var ampm = t[Math.floor(Math.random() * 2)]
return (hr + ':' + mn + ':' + sec + " " + ampm);
}
function getRandomDate() {
var month = getRandInt(13);
var day = getRandInt(28);
return ('2018-' + month + '-' + day);
}
function getRandomEvent() {
var events = ['General Event', 'Random', 'Splash', 'Car crash', 'Touchdown', 'Rain', 'Snow'];
var rand = events[Math.floor(Math.random() * events.length)];
return rand;
}
function getRandomSection(sections) {
var rand = sections[Math.floor(Math.random() * sections.length)];
return rand;
}
function getPopupDivId(t, e, d) {
var popup_div_str = t + e;
var popup_div_id = popup_div_str.replace(/\s{1,}/g, "");
popup_div_id = popup_div_id.replace(/:/g, "");
return popup_div_id;
}
function getDescriptiveDate(dateStr) {
var d_t = dateStr.split("T");
var timeStr = d_t[0] + " " + d_t[1];
console.log(timeStr);
var date = new Date(timeStr + ' UTC');
return "Event time: " + date.toString()
}
function makeTable(eventDetails) {
var d = getDescriptiveDate("2018-11-07T00:49:05");
var popupStr = d + '<br>' + '<table border="1"><tr><th>Parameter Name</th><th>Value</th></tr>';
var data = JSON.parse(eventDetails);
var startTag = '<tr><td>';
var endTag = '</td>';
var rowEnd = '</tr>'
for (var key in data) {
popupStr += (startTag + key + endTag + '<td>' + data[key] + endTag + rowEnd);
}
return popupStr + '</table>';
}
var currentDialog = '';
function setPopupDiv(t, e, d, popup_div_id) {
var table = makeTable('{"Temp": 24, "WindChill": "14", "Dew point": 10}');
var popup_div = '<div id="dialog' + popup_div_id + '\" ' + 'style="display:none">' + table + '</div>';
console.log("setPopupDiv: popup div: " + popup_div);
$('.' + d).append(popup_div);
$('#' + popup_div_id).click(function() {
$(function() {
if (currentDialog == '') {
currentDialog = "#dialog" + popup_div_id;
} else {
console.log('closing dialog' + currentDialog);
$(currentDialog).dialog('close');
currentDialog = "#dialog" + popup_div_id;
}
$("#dialog" + popup_div_id).dialog();
$("#dialog" + popup_div_id).dialog('open');
});
console.log("dialog link click");
return false;
});
}
/* "Create new accordion" button handler */
function addData() {
var d = getRandomDate();
var e = getRandomEvent();
var t = getRandomTime();
var popup_div_id = getPopupDivId(t, e, d);
var ev = '' + t + ' ' + '' + e;
var section = '<h3>' + d + '</h3>';
var dom_element = section + '<div>' + '<ul class=\"' + d + '\">' + '<li>' + ev + '</li></ul>' + '</div>';
$('#accordion').append(dom_element)
.accordion('destroy').accordion({
collapsible: true
});
setPopupDiv(t, e, d, popup_div_id);
console.log("addData(): " + dom_element);
var e2 = getRandomEvent();
var t2 = getRandomTime();
popup_div_id = getPopupDivId(t2, e2, d);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>';
$('.' + d).append(ev2);
setPopupDiv(t2, e2, d, popup_div_id);
}
function addDataActual(eventDate, eventTime, eventType) {
var popup_div_id = getPopupDivId(eventTime, eventType, eventDate);
var evt = '' + eventTime + ' ' + '' + eventType;
var section = '<h3>' + eventDate + '</h3>';
var dom_element = section + '<div>' + '<ul class=\"' + eventDate + '\">' + '<li>' + evt + '</li></ul>' + '</div>';
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
if (this.className == eventDate) {
return this.className;
}
}
}
}).get();
if (arrayOfClassNames.length == 0) {
/* New section */
$('#accordion').append(dom_element)
.accordion('destroy').accordion({
collapsible: true
});
setPopupDiv(eventTime, eventType, eventDate, popup_div_id);
console.log(dom_element);
} else {
/* Exists already*/
d = arrayOfClassNames[0];
popup_div_id = getPopupDivId(eventTime, eventType, d);
var eventToAppend = '<li>' + '' + eventTime + ' ' + '' + eventType + '</li>';
$('.' + d).append(eventToAppend);
setPopupDiv(eventTime, eventType, d, popup_div_id);
}
}
function addDataOrNew() {
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
var toss = getRandInt(2);
if (toss == 0) {
var d = getRandomSection(arrayOfClassNames);
console.log("toss returned 0, adding to existing section " + d);
console.log("Chosen one to add to:" + d);
var e = getRandomEvent();
var t = getRandomTime();
addDataActual(d, t, e);
} else {
var d = getRandomDate();
console.log("toss returned 1, adding a new section " + d);
var e = getRandomEvent();
var t = getRandomTime();
addDataActual(d, t, e);
}
}
function addDataToRandomSection() {
var e = getRandomEvent();
var t = getRandomTime();
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
console.log(arrayOfClassNames);
d = getRandomSection(arrayOfClassNames);
console.log("Chosen one:" + d);
var e2 = getRandomEvent();
var t2 = getRandomTime();
var popup_div_id = getPopupDivId(t2, e2, d);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>'
$('.' + d).append(ev2);
setPopupDiv(t2, e2, d, popup_div_id);
}
function addDataToTopSection() {
var e2 = getRandomEvent();
var t2 = getRandomTime();
var arrayOfClassNames = $("#accordion *").map(function() {
if ($(this).attr('class')) {
if ($(this)[0].nodeName == 'UL') {
return this.className;
}
}
}).get();
d = arrayOfClassNames[0];
var popup_div_id = getPopupDivId(t2, e2, d);
setPopupDiv(t2, e2, d, popup_div_id);
var ev2 = '<li>' + '' + t2 + ' ' + '' + e2 + '</li>'
$('.' + d).append(ev2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href='https://code.jquery.com/ui/1.12.1/themes/cupertino/jquery-ui.css' rel='stylesheet'>
<!doctype html>
<button onclick="addData()" class="regular">Create new Accordion</button>
<button onclick="addDataToRandomSection()" class="regular">Add data to random section</button>
<button onclick="addDataOrNew()" class="regular">Add new section or append to existing</button>
<fieldset id="patient-event-list">
<legend>Event History</legend>
<div id="eventinfo-body">
<button type="button" id="more" onclick="addDataToTopSection()">More history</button>
</div>
<div id="accordion" class="accordion">
</div>
</fieldset>

Related

How to Add Export button in Jquery Custom Datatable

I am using a Web Template for my web site. I am developing with ASP.NET webform. The data will be shown in a Gridview. The Template also has a custom datatable file but without an Export button. I am sharing the js file here. Can anyone help me to edit the jquery and add the export button (PDF, Excel, and Copy)!
Thanks
(function($) {
'use strict';
$.HSCore.components.HSDatatables = {
/**
*
*
* #var Object _baseConfig
*/
_baseConfig: {
paging: true
},
/**
*
*
* #var jQuery pageCollection
*/
pageCollection: $(),
/**
* Initialization of Datatables wrapper.
*
* #param String selector (optional)
* #param Object config (optional)
*
* #return jQuery pageCollection - collection of initialized items.
*/
init: function(selector, config) {
this.collection = selector && $(selector).length ? $(selector) : $();
if (!$(selector).length) return;
this.config = config && $.isPlainObject(config) ?
$.extend({}, this._baseConfig, config) : this._baseConfig;
this.config.itemSelector = selector;
this.initDatatables();
return this.pageCollection;
},
initDatatables: function() {
//Variables
var $self = this,
config = $self.config,
collection = $self.pageCollection;
//Actions
this.collection.each(function(i, el) {
//Variables
var $this = $(el),
$info = $this.data('dt-info'),
$search = $this.data('dt-search'),
$entries = $this.data('dt-entries'),
$pagination = $this.data('dt-pagination'),
$detailsInvoker = $this.data('dt-details-invoker'),
pageLength = $this.data('dt-page-length'),
isResponsive = Boolean($this.data('dt-is-responsive')),
isSelectable = Boolean($this.data('dt-is-selectable')),
isColumnsSearch = Boolean($this.data('dt-is-columns-search')),
isColumnsSearchTheadAfter = Boolean($this.data('dt-is-columns-search-thead-after')),
isShowPaging = Boolean($this.data('dt-is-show-paging')),
scrollHeight = $this.data('dt-scroll-height'),
paginationClasses = $this.data('dt-pagination-classes'),
paginationItemsClasses = $this.data('dt-pagination-items-classes'),
paginationLinksClasses = $this.data('dt-pagination-links-classes'),
paginationNextClasses = $this.data('dt-pagination-next-classes'),
paginationNextLinkClasses = $this.data('dt-pagination-next-link-classes'),
paginationNextLinkMarkup = $this.data('dt-pagination-next-link-markup'),
paginationPrevClasses = $this.data('dt-pagination-prev-classes'),
paginationPrevLinkClasses = $this.data('dt-pagination-prev-link-classes'),
paginationPrevLinkMarkup = $this.data('dt-pagination-prev-link-markup'),
table = $this.DataTable({
pageLength: pageLength,
responsive: isResponsive,
scrollY: scrollHeight ? scrollHeight : '',
scrollCollapse: scrollHeight ? true : false,
paging: isShowPaging ? isShowPaging : config.paging,
drawCallback: function( settings ) {
var api = this.api(),
info = api.page.info();
$($info).html(
'Showing ' + (info.start + 1) + ' to ' + info.end + ' of ' + info.recordsTotal + ' Entries'
);
}
}),
info = table.page.info(),
paginationMarkup = '';
if (scrollHeight) {
$(table.context[0].nScrollBody).mCustomScrollbar({
scrollbarPosition: 'outside'
});
}
$($search).on('keyup', function() {
table.search(this.value).draw();
});
if(isColumnsSearch == true) {
table.columns().every(function () {
var that = this;
if(isColumnsSearchTheadAfter == true) {
$('.dataTables_scrollFoot').insertAfter('.dataTables_scrollHead');
}
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
$('select', this.footer()).on('change', function () {
if (that.search() !== this.value) {
that
.search(this.value)
.draw();
}
});
});
}
$($entries).on('change', function() {
var val = $(this).val();
table.page.len(val).draw();
// Pagination
if (isShowPaging == true) {
$self.pagination($pagination, table, paginationClasses, paginationItemsClasses, paginationLinksClasses, paginationNextClasses, paginationNextLinkClasses, paginationNextLinkMarkup, paginationPrevClasses, paginationPrevLinkClasses, paginationPrevLinkMarkup, val);
}
});
if(isSelectable == true) {
$($this).on('change', 'input', function() {
$(this).parents('tr').toggleClass('checked');
})
}
// Pagination
if (isShowPaging == true) {
$self.pagination($pagination, table, paginationClasses, paginationItemsClasses, paginationLinksClasses, paginationNextClasses, paginationNextLinkClasses, paginationNextLinkMarkup, paginationPrevClasses, paginationPrevLinkClasses, paginationPrevLinkMarkup, info.pages);
}
// Details
$self.details($this, $detailsInvoker, table);
//Actions
collection = collection.add($this);
});
},
pagination: function(target, table, pagiclasses, pagiitemclasses, pagilinksclasses, paginextclasses, paginextlinkclasses, paginextlinkmarkup, pagiprevclasses, pagiprevlinkclasses, pagiprevlinkmarkup, pages) {
var info = table.page.info(),
paginationMarkup = '';
for (var i = 0; i < info.recordsTotal; i++) {
if (i % info.length == 0) {
paginationMarkup += i / info.length == 0 ? '<li class="' + pagiitemclasses + '"><a id="datatablePaginationPage' + (i / info.length) + '" class="' + pagilinksclasses + ' active" href="#!" data-dt-page-to="' + (i / info.length) + '">' + ((i / info.length) + 1) + '</a></li>' : '<li class="' + pagiitemclasses + '"><a id="' + target + (i / info.length) + '" class="' + pagilinksclasses + '" href="#!" data-dt-page-to="' + (i / info.length) + '">' + ((i / info.length) + 1) + '</a></li>';
}
}
$('#' + target).html(
'<ul class="' + pagiclasses + '">\
<li class="' + pagiprevclasses + '">\
<a id="' + target + 'Prev" class="' + pagiprevlinkclasses + '" href="#!" aria-label="Previous">' + pagiprevlinkmarkup + '</a>\
</li>' +
paginationMarkup +
'<li class="' + paginextclasses + '">\
<a id="' + target + 'Next" class="' + paginextlinkclasses + '" href="#!" aria-label="Next">' + paginextlinkmarkup + '</a>\
</li>\
</ul>'
);
$('#' + target + ' [data-dt-page-to]').on('click', function() {
var $page = $(this).data('dt-page-to'),
info = table.page.info();
$('#' + target + ' [data-dt-page-to]').removeClass('active');
$(this).addClass('active');
table.page($page).draw('page');
});
$('#' + target + 'Next').on('click', function() {
var $currentPage = $('#' + target + ' [data-dt-page-to].active');
table.page('next').draw('page');
if ($currentPage.parent().next().find('[data-dt-page-to]').length) {
$('#' + target + ' [data-dt-page-to]').removeClass('active');
$currentPage.parent().next().find('[data-dt-page-to]').addClass('active');
} else {
return false;
}
});
$('#' + target + 'Prev').on('click', function() {
var $currentPage = $('#' + target + ' [data-dt-page-to].active');
table.page('previous').draw('page');
if ($currentPage.parent().prev().find('[data-dt-page-to]').length) {
$('#' + target + ' [data-dt-page-to]').removeClass('active');
$currentPage.parent().prev().find('[data-dt-page-to]').addClass('active');
} else {
return false;
}
});
},
format: function(value) {
return value;
},
details: function(el, invoker, table) {
if (!invoker) return;
//Variables
var $self = this;
$(el).on('click', invoker, function() {
var tr = $(this).closest('tr'),
row = table.row(tr);
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('opened');
} else {
row.child($self.format(tr.data('details'))).show();
tr.addClass('opened');
}
});
}
};
})(jQuery);

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);
}

Highlight.js and Showdown.js not work together

I am trying to be able to use highlight.js when my preview is enabled
Unable to get the highlightjs to work with my preview using showdown.js
Question: How to get the highlight.js to work with showdown.js
Codepen Demo Note all the .js files and css files are loaded in the codepen settings
I have tried using
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
Full Script
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
})
$('#button-link').on('click', function() {
$('#myLink').modal('show');
});
$('#button-image').on('click', function() {
$('#myImage').modal('show');
});
$('#button-smile').on('click', function() {
$('#mySmile').modal('show');
});
$('#myLink').on('shown.bs.modal', function() {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
$('#link_title').val(selectedText);
$('#link_url').val('http://');
});
$('#myImage').on('shown.bs.modal', function() {
$("#image_url").attr("placeholder", "http://www.example.com/image.png");
});
$("#save-image").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
var replace_word = '![enter image description here]' + '[' + counter + ']';
if (counter == 1) {
if ($('input#image_width').val().length > 0) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val() + ' =' + $('input#image_width').val() + 'x' + $('input#image_height').val();
} else {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#image_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
$("#save-link").on('click', function(e) {
var textarea = document.getElementById("message");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var selectedText = textarea.value.substring(start, end);
var counter = findAvailableNumber(textarea);
if ($('#link_title').val().length > 0) {
var replace_word = '[' + $('#link_title').val() + ']' + '[' + counter + ']';
} else {
var replace_word = '[enter link description here]' + '[' + counter + ']';
}
if (counter == 1) {
var add_link = '\n\n' + ' [' + counter + ']: ' + $('#link_url').val();
} else {
var add_link = '\n' + ' [' + counter + ']: ' + $('#link_url').val();
}
textarea.value = textarea.value.substring(0, start) + replace_word + textarea.value.substring(end, len) + add_link;
$("#message").trigger('change');
});
// Editor Buttons
$('#bold').on('click', function(e) {
text_wrap("message", "**", "**", 'strong text');
});
$('#italic').on('click', function(e) {
text_wrap("message", "*", "*", 'emphasized text');
});
$('#quote').on('click', function(e) {
text_wrap("message", "> ", "", 'Blockquote');
});
$('#code').on('click', function(e) {
code_wrap("message", "", "", 'enter code here');
});
function text_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
if (selectedText.length > 0) {
replacement = openTag + selectedText + closeTag;
} else {
replacement = openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function code_wrap(elementID, openTag, closeTag, message) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var multiLineReplace = '\n' + openTag;
if (selectedText.length > 0) {
//using regex to replace all instances of `\n` with `\n` + your indent spaces.
replacement = ' ' + openTag + selectedText.replace(/\n/g, multiLineReplace) + closeTag;
} else {
replacement = ' ' + openTag + message + closeTag;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
function findAvailableNumber(textarea) {
var number = 1;
var a = textarea.value;
if (a.indexOf('[1]') > -1) {
//Find lines with links
var matches = a.match(/(^|\n)\s*\[\d+\]:/g);
//Find corresponding numbers
var usedNumbers = matches.map(function(match) {
return parseInt(match.match(/\d+/)[0]);
});
//Find first unused number
var number = 1;
while (true) {
if (usedNumbers.indexOf(number) === -1) {
//Found unused number
return number;
}
number++;
}
}
return number;
}
$("#message").on('keyup paste cut', function() {
var text = document.getElementById('message').value,
target = document.getElementById('showdown'),
converter = new showdown.Converter({
parseImgDimensions: true
}),
html = converter.makeHtml(text);
target.innerHTML = html;
});
$(function() {
$('[data-toggle="tooltip"]').tooltip()
});

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.

multiple onload error in HTML

HTML:-
In the body tag I have used onload="variable2.init() ; variable1.init();".
JavaScript:-
var variable1 = {
rssUrl: 'http://feeds.feedburner.com/football-italia/pAjS',
init: function() {
this.getRSS();
},
getRSS: function() {
jQuery.getFeed({
url: variable1.rssUrl,
success: function showFeed(feed) {
variable1.parseRSS(feed);
}
});
},
parseRSS: function(feed) {
var main = '';
var posts = '';
var className = 'even';
var pst = {};
for (i = 0; i < feed.items.length; i++) {
pst = variable1.parsefootballitaliaRSS(feed.items[i]);
if (className == 'odd') {
className = 'even';
}
else {
className = 'odd';
}
var shorter = pst.story.replace(/<(?:.|\n)*?>/gm, '');
item_date = new Date(feed.items[i].updated);
main += '<div id="content1" class="post-main ' + className + '" onclick="mwl.setGroupTarget(\'#screens1\', \'#blog_posts1\', \'ui-show\', \'ui-hide\');mwl.setGroupTarget(\'#blog_posts1\', \'#post' + (i+1) + '\', \'ui-show\', \'ui-hide\');">';
main += '<b>' + pst.title.trunc(55, true) + '</b><br />' + shorter.trunc(30, true);
main += '<div class="datetime">' + item_date.getDateTime() + '</div></div>';
posts += '<div class="post-wrapper ui-hide" id="post' + (i+1) + '">';
posts += '<div class="post-title"><b>' + pst.title + '</b></div>';
posts += feed.items[i].description;
posts += '</div>';
}
jQuery('#main_screen1').html(main);
jQuery('#blog_posts1').html(posts);
},
parsefootballitaliaRSS: function(item) {
var match = item.description.match('src="([^"]+)"');
var part = item.description.split('<font size="-1">');
var arr = {
title: item.title,
link: item.link,
image: match,
site_title: item.title,
story: item.description
};
return arr;
}
};
var variable2 = {
weatherRSS: 'http://feeds.feedburner.com/go/ELkW',
init: function() {
this.getWeatherRSS();
},
getWeatherRSS: function() {
jQuery.getFeed({
url: variable2.weatherRSS,
success: function showFeed(feed) {
variable2.parseWeather(feed);
}
});
},
parseWeather: function(feed) {
var main = '';
var posts = '';
var className = 'even';
var pst = {};
for (i = 0; i < feed.items.length; i++) {
pst = variable2.parsegoRSS(feed.items[i]);
if (className == 'odd') {
className = 'even';
}
else {
className = 'odd';
}
var shorter = pst.story.replace(/<(?:.|\n)*?>/gm, '');
item_date = new Date(feed.items[i].updated);
main += '<div id="content2" class="post-main ' + className + '" onclick="mwl.setGroupTarget(\'#screens2\', \'#blog_posts2\', \'ui-show\', \'ui-hide\');mwl.setGroupTarget(\'#blog_posts2\', \'#post' + (i+1) + '\', \'ui-show\', \'ui-hide\');">';
main += '<b>' + pst.title.trunc(55, true) + '</b><br />' + shorter.trunc(30, true);
main += '<div class="datetime">' + item_date.getDateTime() + '</div></div>';
posts += '<div class="post-wrapper ui-hide" id="post' + (i+1) + '">';
posts += '<div class="post-title"><b>' + pst.title + '</b></div>';
posts += feed.items[i].description;
posts += '</div>';
}
jQuery('#main_screen2').html(main);
jQuery('#blog_posts2').html(posts);
},
parsegoRSS: function(item) {
var match = item.description.match('src="([^"]+)"');
var part = item.description.split('<font size="-1">');
var arr = {
title: item.title,
link: item.link,
image: match,
site_title: item.title,
story: item.description
};
return arr;
}
};
When I run the program it only reads one of the variables i.e. either 1 or 2.
How can I correct them to read both the variables?
Use this.
<script type="text/javascript">
window.onload = function() {
variable1.init();
variable2.init();
}
</script>
Try this
<body onload="callFunctions()">
JS-
function callFunctions()
{
variable1.init();
variable2.init();
}
Update-
Also
there are other different ways to call multiple functions on page load
Hope it hepls you.

Categories

Resources