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);
Related
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');
}
});
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.
I am triggering a change event on a combo box for multiple values but unfortunately events are getting lost. Is there a way to wait for one event to complete before triggering the next event. Sample code is shown below
for (i = 0; i < contextFilters.length; i++)
{
var contextFilter = contextFilters[i];
if (contextFilter != "")
{
var cfData = contextFilter.split(":");
var cfName = cfData[0];
var cfVal = cfData[1];
if (cfName != null)
{
//alert("cfName : " + cfName);
//alert("cfVal : " + cfVal);
$('#context_filter').val(cfName);
$('#context_filter').trigger('change', cfVal);
}
}
}
When the event is triggered a new select box is added to the DOM but not all select boxes are getting added.
Also the change event handler is a s shown below
$('#context_filter').change(function(event, selectValues)
{
if ($(this).prop("selectedIndex") > 0)
{
populateDateValues();
var contextFilterComboObject = $(this);
var selectedVal = $(contextFilterComboObject).val();
var validate = $('#collapsiblePanel :input').attr('disabled') == null;
if (!validate)
{
$('table[id*=OtherOptions] :input').attr('disabled', false);
$('#collapsiblePanel :input').attr('disabled', false);
}
var formInput = decodeURIComponent($('#rptInputParams').serialize());
formInput += "&validate=" + validate;
$('#ajaxBusy').show();
$.getJSON('GetContextFilterData', formInput, function(data)
{
var selectBox = '<tr><td class="celltoppad"><b>' + selectedVal +
' : </b></td> <td class="celltoppad"><select multiple="multiple" name="' +
selectedVal.toLowerCase() + '" id="' + selectedVal.toLowerCase() + '" >';
var errorMsg = '';
var errorCount = 1;
errorMsg += '<html>';
$.each(data.errorMessageList, function(index, value)
{
errorMsg += errorCount + ') ' + value + '</br></br>';
errorCount++;
});
errorMsg += '</html>';
if (errorCount > 1)
{
$('#ajaxBusy').hide();
showErrorDialog(errorMsg, errorCount * 20);
$(contextFilterComboObject).prop("selectedIndex", '0');
return;
}
$.each(data.contextFilterDataList, function(index, value)
{
selectBox += '<option value="' + value + '">' + value + "</option>";
});
selectBox +=
'</select></td><td class="celltoppad"><a href="#"><img id="removeCF" ' +
'src="../images/remove.png"/></a></td></tr>';
$('#ajaxBusy').hide();
// If the context filter has not been already added.
if ($('#' + selectedVal.toLowerCase()).length == 0)
{
$('a[id*=_showDialog]').hide();
toggleDatePickerLink();
$('img#removeDate').hide();
$('table[id*=OtherOptions] :input').attr('disabled', true);
$('#collapsiblePanel :input').attr('disabled', true);
$('table#context_filter').append(selectBox);
$(contextFilterComboObject).prop("selectedIndex", '0');
}
if (selectValues != null)
{
$('#' + selectedVal.toLowerCase()).val(selectValues.split(","));
}
$('#' + selectedVal.toLowerCase()).multiselect({
noneSelectedText: 'Please select',
selectedList: 3,
selectedText: '# of # selected',
position: {
my: 'left center',
at: 'right center',
offset: '20 100'
}
}).multiselectfilter();
});
}
});
instead of triggering the event, can't you just call the handler ?
var handler = function(event, selectValues)
{
if ($('#context_filter').prop("selectedIndex") > 0)
{
populateDateValues();
var contextFilterComboObject = $('#context_filter');
var selectedVal = $(contextFilterComboObject).val();
var validate = $('#collapsiblePanel :input').attr('disabled') == null;
if (!validate)
{
$('table[id*=OtherOptions] :input').attr('disabled', false);
$('#collapsiblePanel :input').attr('disabled', false);
}
var formInput = decodeURIComponent($('#rptInputParams').serialize());
formInput += "&validate=" + validate;
$('#ajaxBusy').show();
$.getJSON('GetContextFilterData', formInput, function(data)
{
var selectBox = '<tr><td class="celltoppad"><b>' + selectedVal +
' : </b></td> <td class="celltoppad"><select multiple="multiple" name="' +
selectedVal.toLowerCase() + '" id="' + selectedVal.toLowerCase() + '" >';
var errorMsg = '';
var errorCount = 1;
errorMsg += '<html>';
$.each(data.errorMessageList, function(index, value)
{
errorMsg += errorCount + ') ' + value + '</br></br>';
errorCount++;
});
errorMsg += '</html>';
if (errorCount > 1)
{
$('#ajaxBusy').hide();
showErrorDialog(errorMsg, errorCount * 20);
$(contextFilterComboObject).prop("selectedIndex", '0');
return;
}
$.each(data.contextFilterDataList, function(index, value)
{
selectBox += '<option value="' + value + '">' + value + "</option>";
});
selectBox +=
'</select></td><td class="celltoppad"><a href="#"><img id="removeCF" ' +
'src="../images/remove.png"/></a></td></tr>';
$('#ajaxBusy').hide();
// If the context filter has not been already added.
if ($('#' + selectedVal.toLowerCase()).length == 0)
{
$('a[id*=_showDialog]').hide();
toggleDatePickerLink();
$('img#removeDate').hide();
$('table[id*=OtherOptions] :input').attr('disabled', true);
$('#collapsiblePanel :input').attr('disabled', true);
$('table#context_filter').append(selectBox);
$(contextFilterComboObject).prop("selectedIndex", '0');
}
if (selectValues != null)
{
$('#' + selectedVal.toLowerCase()).val(selectValues.split(","));
}
$('#' + selectedVal.toLowerCase()).multiselect({
noneSelectedText: 'Please select',
selectedList: 3,
selectedText: '# of # selected',
position: {
my: 'left center',
at: 'right center',
offset: '20 100'
}
}).multiselectfilter();
});
}
});
for (i = 0; i < contextFilters.length; i++)
{
var contextFilter = contextFilters[i];
if (contextFilter != "")
{
var cfData = contextFilter.split(":");
var cfName = cfData[0];
var cfVal = cfData[1];
if (cfName != null)
{
//alert("cfName : " + cfName);
//alert("cfVal : " + cfVal);
$('#context_filter').val(cfName);
handler(null, cfVal);
}
}
}
I never tested above code, but I declared your handler as a function and then in the loop at the bottom, you can see how I call it instead of triggering it (handler(cfVal))
I was able to figure out the solution to my problem, when the back button is clicked and the change event is fired then I made the ajax call using async as false and that resolved the issue. This is because if the async is true json calls happen simultaneously and some events are lost during that period.
Thanks
I have a website which includes this RSS JavaScript. When I click feed, it opens same page, but I don't want to do that. How can I open with blank page? I have my current HTML and JavaScript below.
HTML CODE
<tr>
<td style="background-color: #808285" class="style23" >
<script type="text/javascript">
$(document).ready(function () {
$('#ticker1').rssfeed('http://www.demircelik.com.tr/map.asp').ajaxStop(function () {
$('#ticker1 div.rssBody').vTicker({ showItems: 3 });
});
});
</script>
<div id="ticker1" >
<br />
</div>
</td>
</tr>
JAVASCRIPT CODE
(function ($) {
var current = null;
$.fn.rssfeed = function (url, options) {
// Set pluign defaults
var defaults = {
limit: 10,
header: true,
titletag: 'h4',
date: true,
content: true,
snippet: true,
showerror: true,
errormsg: '',
key: null
};
var options = $.extend(defaults, options);
// Functions
return this.each(function (i, e) {
var $e = $(e);
// Add feed class to user div
if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
// Check for valid url
if (url == null) return false;
// Create Google Feed API address
var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
if (options.limit != null) api += "&num=" + options.limit;
if (options.key != null) api += "&key=" + options.key;
// Send request
$.getJSON(api, function (data) {
// Check for error
if (data.responseStatus == 200) {
// Process the feeds
_callback(e, data.responseData.feed, options);
}
else {
// Handle error if required
if (options.showerror) if (options.errormsg != '') {
var msg = options.errormsg;
}
else {
var msg = data.responseDetails;
};
$(e).html('<div class="rssError"><p>' + msg + '</p></div>');
};
});
});
};
// Callback function to create HTML result
var _callback = function (e, feeds, options) {
if (!feeds) {
return false;
}
var html = '';
var row = 'odd';
// Add header if required
if (options.header) html += '<div class="rssHeader">' + '' + feeds.title + '' + '</div>';
// Add body
html += '<div class="rssBody">' + '<ul>';
// Add feeds
for (var i = 0; i < feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
// Add feed row
html += '<li class="rssRow ' + row + '">' + '<' + options.titletag + '>' + entry.title + '</' + options.titletag + '>'
if (options.date) html += '<div>' + pubDate + '</div>'
if (options.content) {
// Use feed snippet if available and optioned
if (options.snippet && entry.contentSnippet != '') {
var content = entry.contentSnippet;
}
else {
var content = entry.content;
}
html += '<p>' + content + '</p>'
}
html += '</li>';
// Alternate row classes
if (row == 'odd') {
row = 'even';
}
else {
row = 'odd';
}
}
html += '</ul>' + '</div>'
$(e).html(html);
};
})(jQuery);
try change this:
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
to
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
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>