Triggering change events in a loop results in loss events - javascript

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

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

problems with storing getjson request in variable

I'm having troubles with getting a variable from a getJSON() request. I have the following three functions:
function getPcLatitude() { // onchange
var funcid = "get_postcode_latitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLatitude) {
if (dataLatitude == null) {
//..
} else {
var myLatitude = 0;
for (var i=0;i<dataLatitude.length;i++){
myLatitude = dataLatitude[i].pc_latitude;
}
return parseFloat(myLatitude);
//alert(myLatitude);
}
});
}
function getPcLongitude() { // onchange
var funcid = "get_postcode_longitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLongitude) {
if (dataLongitude == null) {
//..
} else {
var myLongitude = 0;
for (var i=0;i<dataLongitude.length;i++){
myLongitude = dataLongitude[i].pc_longitude;
}
return parseFloat(myLongitude);
//alert(myLongitude);
}
});
}
function getTop5Postcode() { // onchange
setTimeout(function() {
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var latitude = getPcLatitude();
var longitude = getPcLongitude();
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}, 0);
}
Form some reason the
var latitude = getPcLatitude();
var longitude = getPcLongitude();
parts don't work / don't get a value form the functions. When I change the return in both functions into an alert() it does give me the expected values, so those two functions work.
When I set the two variables directly, like so:
var latitude = 5215;
var longitude = 538;
then the getTop5Postcode() function does work and fills the table.
Any help on this?
Regards, Bart
Do not forget that JavaScript is asynchronous, so by the time you reach the return statement, the request is probably not done yet. You can use a promise, something like:
$.getJSON(....).then(function(value){//do what you want to do here})
Both your functions (getPcLatitude and getPcLongitude) are returning nothing because the return statement is inside a callback from an asynchronous request, and that's why an alert show the correct value.
I would suggest you to change both methods signature adding a callback parameter.
function getPcLatitude(callback) {
...
}
function getPcLongitude(callback) {
...
}
And instead of returning you should pass the value to the callback:
callback(parseFloat(myLatitude));
callback(parseFloat(myLongitude));
And your last function would be somehting like that:
function getTop5Postcode() { // onchange
setTimeout(function() {
var latitude;
var longitude;
getPcLatitude(function(lat) {
latitude = lat;
getTop5(); // Here you call the next function because you can't be sure what response will come first.
});
getPcLongitude(function(longi) {
longitude = longi;
getTop5();
});
function getTop5() {
if (!latitude || !longitude) {
return; // This function won't continue if some of the values are undefined, null, false, empty or 0. You may want to change that.
}
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}
}, 0);
}
Of course, this is far away from the perfect solution for your problem but it should work!
And I did not test this code.
I solved this by doing some extra stuff in mysql queries. Now I only have to use the main function.
Things work now! Thanks for all the help!

Autocompleting textbox from jquery combobox

I have been following an online tutorial to autocomplete textboxes with database values after the user enters a code greater than 7 characters. I have completed most of what I am trying to achieve however I cannot seem to select a value from the combobox to autocomplete the textbox.
I dont have much javascript experience but I am hoping the problem is something small in what I already have, can someone please recommend the change I need to make to select the value from the combobox.
public ActionResult MultiColumnComboBox(string SearchFor, string ControlId)
{
ViewBag.ProcId = SearchFor.Trim();
ViewBag.ControlBlockId = "block" + ControlId.Trim();
ViewBag.ControlId = ControlId.Trim();
ViewBag.ControlTxtId = "txt" + ControlId.Trim();
return View();
}
public JsonResult LoadComboData(string strSearch, string SearchFor)
{
efacsdbEntities db = new efacsdbEntities();
strSearch = strSearch.Trim();
if (SearchFor.Trim() == "employee" && strSearch.Length>7)
{
var res = (from E in db.allpartmasters
where E.partnum.ToLower().Contains(strSearch.ToLower()) || E.partdesc.ToLower().Contains(strSearch.ToLower())
select new
{
E.partnum,
E.partdesc
}).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
<input type="hidden" id="#ViewBag.ProcId" name="#ViewBag.ProcId" value="" />
<input type="hidden" id="#ViewBag.ControlId" name="#ViewBag.ControlId" value="" />
<input type="text" name="#ViewBag.ControlTxtId" id="#ViewBag.ControlTxtId" autocomplete="on" />
<div class="#ViewBag.ControlTxtId renderpart">
<div class="DataBlock">
<div id="#ViewBag.ControlBlockId" style="max-width: 520px;">
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../Scripts/json.debug.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".renderpart").hide();
var txtid = "#" + '#ViewBag.ControlTxtId';
var renderpart = "." + '#ViewBag.ControlTxtId';
var selectlinkvalueid = ".Get" + '#ViewBag.ProcId';
$(selectlinkvalueid).on("click", function () {
var value = $(this).attr('id');
var valueText = $(this).attr('title');
$("##ViewBag.ControlId").val(value);
$(txtid).val(valueText);
$(renderpart).slideUp("slow");
});
$(txtid).keyup(function () {
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var activecols = $("#hdnActiveColumns").val();
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
$(txtid).focusin(function () {
var txtid = "#" + '#ViewBag.ControlTxtId';
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
function CreateDynamicTable(objArray, tempprocId) {
var array = JSON.parse(objArray);
var str = '<table style="width:100%;">';
str += '<tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr>';
str += '<tbody>';
var flag = false;
var ids;
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr>' : '<tr>';
for (var index in array[i]) {
if (flag == false) {
ids = array[i][index];
flag = true;
}
str += '<td><a id="' + ids + '" class="Get' + tempprocId + '" title="' + array[i][index] + '" href="#">' + array[i][index] + '</a></td>';
}
str += '</tr>';
}
str += '</tbody>';
str += '</table>';
return str;
}
});
$(document).click(function (evt) {
var renderpart = "." + '#ViewBag.ControlTxtId';
var theElem = (evt.srcElement) ? evt.srcElement : evt.target;
if (theElem.id == "main" || theElem.id == "sub1") {
$(renderpart).slideUp("fast");
}
});
</script>
Here is the link to the tutorial I was following as well.
Create Multiple column autocomplete combobox

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.

How can I open with blank page on this rss javascript nor html?

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 +'>'

Categories

Resources