jquery checkbox listener for loop - javascript

SOLUTION
https://github.com/Campos696/Attendance/commit/28177ff5cf285e9616faddae74fa6f0288a8667a
i have this javascript file:
https://github.com/Campos696/Attendance/blob/master/js/app.js
and am trying to make it so that the checkboxes created by the bodyView, have click listeners, however right now i can only create a listener for one checkbox at a time, is there any way to improve this?
And whether i check or uncheck it does the same thing(decreases daysMissed).
Here is the relevant part of the code:
var bodyView = {
init: function() {
this.render();
},
render: function() {
var student, i, x;
var schoolDays = octopus.getSchoolDays();
var students = octopus.getStudents();
for(i = 0;i < students.length; i++) {
octopus.setCurrentStudent(students[i]);
var daysMissed = octopus.getDaysMissed();
$('#students').append('<tr class="'+i+'"><td class="name-col">' + students[i].name + '</td></tr>');
for(x = 1;x < schoolDays; x++) {
$('.'+i).append('<td id="check'+i+'" class="attend-col"><input type="checkbox"></td>');
};
$('.'+i).append('<td class="missed-col">'+ daysMissed + '</td>');
};
$(function(){
$('#check0').click(function() {
octopus.setCurrentStudent(students[0]);
if($(this).is(':checked')){
octopus.incrementDaysMissed();
} else if(!$(this).is(':checked')){
octopus.decreaseDaysMissed();
}
})
})
}
}
FUNCTION EDIT
$(function(){
$('[id^=check] :checkbox').on('change', function(e) {
var daysMissed = $(this).closest('tr').find('td:last');
if (this.checked) {
octopus.decreaseDaysMissed();
daysMissed.html(octopus.getDaysMissed());
} else {
octopus.incrementDaysMissed();
daysMissed.html(octopus.getDaysMissed());
}
})
})

IDs must be unique. That means you need to change the following line:
$('.'+i).append('<td id="check'+i+'" class="attend-col"><input type="checkbox"></td>');
with:
$('.'+i).append('<td id="check'+ i + x +'" class="attend-col"><input type="checkbox"></td>');
^^^^^^^^
In this way each td has an id like: check01.....check46...
Second issue: change the click event with the change event and attach it to:
$('[id^=check] :checkbox').on('change', function(e) {
select each td having an id starting with check and for each td get the child checkbox.
var model = {
currentStudent: null,
schoolDays: 12,
students: [
{
name: "Slappy the Frog",
daysMissed: 12
},
{
name: "Lilly the Lizard",
daysMissed: 12
},
{
name: "Paulrus the Walrus",
daysMissed: 12
},
{
name: "Gregory the Goat",
daysMissed: 12
},
{
name: "Adam the Anaconda",
daysMissed: 12
}
]
};
// Octopus
var octopus = {
init: function () {
model.currentStudent = model.students[0];
headerView.init();
bodyView.init();
},
getStudents: function () {
return model.students;
},
setCurrentStudent: function (student) {
model.currentStudent = student;
},
getSchoolDays: function () {
return model.schoolDays + 1;
},
getDaysMissed: function () {
return model.currentStudent.daysMissed;
},
incrementDaysMissed: function () {
model.currentStudent.daysMissed++;
},
decreaseDaysMissed: function () {
model.currentStudent.daysMissed--;
}
};
// View
var headerView = {
init: function () {
this.render();
},
render: function () {
var i;
var schoolDays = octopus.getSchoolDays();
$('#header').append('<th class="name-col">Student Name</th>');
for (i = 1; i < schoolDays; i++) {
$('#header').append('<th>' + i + '</th>');
}
;
$('#header').append('<th class="missed-col">Days Missed</th>');
}
};
var bodyView = {
init: function () {
this.render();
},
render: function () {
var student, i, x;
var schoolDays = octopus.getSchoolDays();
var students = octopus.getStudents();
$('#students').empty();
for (i = 0; i < students.length; i++) {
octopus.setCurrentStudent(students[i]);
var daysMissed = octopus.getDaysMissed();
$('#students').append('<tr class="' + i + '"><td class="name-col">' + students[i].name + '</td></tr>');
for (x = 1; x < schoolDays; x++) {
$('.' + i).append('<td id="check' + i + x + '" class="attend-col"><input type="checkbox"></td>');
}
$('.' + i).append('<td class="missed-col">' + daysMissed + '</td>');
}
$(function(){
$('[id^=check] :checkbox').on('change', function(e) {
var colId = $(this).closest('td').index();
var rowId = $(this).closest('tr').index();
var studentName =
$(this).closest('tr').find('td:first').text();
console.log('Student: <' + studentName +
'> on day: ' + colId + ' changed to: ' +
this.checked + ' Col: ' + colId + ' Row: ' + rowId);
})
})
}
}
$(function () {
octopus.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/Campos696/Attendance/master/css/style.css">
<h1>Udacity Attendance</h1>
<table>
<thead>
<tr id="header"></tr>
</thead>
<tbody id="students"></tbody>
</table>

Use the input:checkbox selector to get all checkboxes:
$(function(){
$("input:checkbox").click(function() {
octopus.setCurrentStudent(students[0]);
if($(this).prop("checked",true)){
octopus.incrementDaysMissed();
} else {
octopus.decreaseDaysMissed();
}
});
});

Related

Javascript for loop index starting from the max number

I need a solution on how to get this solved. javascript loop function not working well in AJAX return function.
var selectedColor = '';
var selectedSize = '';
var selectedQuantity = '';
var productID = '';
var indexCount;
$('.up-cart').on('click', function() {
var cartRows = $('.cartRows').length;
for (indexCount = 0; indexCount <= cartRows; indexCount++) {
$('.myOrderSettings [name="selectedColor' + indexCount + '"]').each(function() {
if ($(this).prop("checked")) {
if (selectedColor == "") {
selectedColor += $(this).val();
} else {
selectedColor += ',' + $(this).val();
}
}
});
$('.myOrderSettings [name="selectedSize' + indexCount + '"]').each(function() {
if ($(this).prop("checked")) {
if (selectedSize == "") {
selectedSize += $(this).val();
} else {
selectedSize += ',' + $(this).val();
}
}
});
$('.myOrderSettings [name="selectedQuantity' + indexCount + '"]').each(function() {
if ($(this).val() < 1) {
selectedQuantity = '1';
alertMe("Your order quantity has been set to 1", 5000);
}
if (parseInt($(this).val()) > parseInt($(this).attr('max'))) {
selectedQuantity = $(this).attr('max');
alertMe("We have " + $(this).attr('max') + " of this product. Your order quantity has been set to " + $(this).attr('max'), 5000);
} else {
selectedQuantity = $(this).val();
}
});
productID = $('.myOrderSettings [name="productID' + indexCount + '"]').val();
$.ajax({
url: "<?php echo base_url() ?>cart/updateCart",
type: "post",
dataType: "json",
data: {
selectedColor: selectedColor,
selectedSize: selectedSize,
selectedQuantity: selectedQuantity,
productID: productID
},
success: function(data) {
console.log(indexCount);
$('.myOrderSettings .t-total' + indexCount).html(formatMoney(parseInt(data.cart_amount)));
}
});
calculateTotalAmount();
selectedColor = "";
selectedSize = "";
selectedQuantity = "";
productID = "";
}
});
The result on the console I get in console is 6 meanwhile I have a total of 5 rows. This is hindering me from returning the result to the objects respectively. Check the result in the console
I just got it solved, I noticed async wasn't set to false so here's my solution. but other solutions would be welcomed.
var selectedColor = '';
var selectedSize = '';
var selectedQuantity = '';
var productID = '';
var indexCount;
$('.up-cart').on('click', function() {
var cartRows = $('.cartRows').length;
for (indexCount = 0; indexCount <= cartRows; indexCount++) {
$('.myOrderSettings [name="selectedColor' + indexCount + '"]').each(function() {
if ($(this).prop("checked")) {
if (selectedColor == "") {
selectedColor += $(this).val();
} else {
selectedColor += ',' + $(this).val();
}
}
});
$('.myOrderSettings [name="selectedSize' + indexCount + '"]').each(function() {
if ($(this).prop("checked")) {
if (selectedSize == "") {
selectedSize += $(this).val();
} else {
selectedSize += ',' + $(this).val();
}
}
});
$('.myOrderSettings [name="selectedQuantity' + indexCount + '"]').each(function() {
if ($(this).val() < 1) {
selectedQuantity = '1';
alertMe("Your order quantity has been set to 1", 5000);
}
if (parseInt($(this).val()) > parseInt($(this).attr('max'))) {
selectedQuantity = $(this).attr('max');
alertMe("We have " + $(this).attr('max') + " of this product. Your order quantity has been set to " + $(this).attr('max'), 5000);
} else {
selectedQuantity = $(this).val();
}
});
productID = $('.myOrderSettings [name="productID' + indexCount + '"]').val();
$.ajax({
url: "<?php echo base_url() ?>cart/updateCart",
type: "post",
dataType: "json",
async: false,
data: {
selectedColor: selectedColor,
selectedSize: selectedSize,
selectedQuantity: selectedQuantity,
productID: productID
},
success: function(data) {
console.log(indexCount);
$('.myOrderSettings .t-total' + indexCount).html(formatMoney(parseInt(data.cart_amount)));
}
});
calculateTotalAmount();
selectedColor = "";
selectedSize = "";
selectedQuantity = "";
productID = "";
}
});
This is happening because you are iterating from 0 to cartRows. It needs to be 0 to one less than cartRows.
....
for (indexCount = 0; indexCount < cartRows; indexCount++) {
//Your code
}
cartRows storing length of $('.cartRows'). In Javascript .length returns number of elements present in an array. When you iterate your for loop should iterate for $('.cartRows').lenght number of times.
As you are starting index from 0 to <= $('.cartRows').length, your for loop will iterate length + 1 number of times (because of <=)

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

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

Appending a class to a javascript calendar given the data (clndr.js)

I am looking to assign a class to each clndr.js event that appears in my calendar based on the value itself. var temp shows an example of the data received. I want to the style each event on type being 1 or 2. The code shows the default template which I want to modify to simply add in the value passed in type as a class so I can then style it.
link to the source library on github
link to a similar problem on github
// This is the default calendar template. This can be overridden.
var clndrTemplate =
"<div class='clndr-controls'>" +
"<div class='clndr-control-button'>" +
"<span class='clndr-previous-button'>previous</span>" +
"</div>" +
"<div class='month'><%= month %> <%= year %></div>" +
"<div class='clndr-control-button rightalign'>" +
"<span class='clndr-next-button'>next</span>" +
"</div>" +
"</div>" +
"<table class='clndr-table' border='0' cellspacing='0' cellpadding='0'>" +
"<thead>" +
"<tr class='header-days'>" +
"<% for(var i = 0; i < daysOfTheWeek.length; i++) { %>" +
"<td class='header-day'><%= daysOfTheWeek[i] %></td>" +
"<% } %>" +
"</tr>" +
"</thead>" +
"<tbody>" +
"<% for(var i = 0; i < numberOfRows; i++){ %>" +
"<tr>" +
"<% for(var j = 0; j < 7; j++){ %>" +
"<% var d = j + i * 7; %>" +
"<td class='<%= days[d].classes %>'>" +
"<div class='day-contents <%= days[d].type %>'><%= days[d].day %></div>" +
"</td>" +
"<% } %>" +
"</tr>" +
"<% } %>" +
"</tbody>" +
"</table>";
var calendars = {};
$(document).ready(function () {
var thisMonth = moment().format('YYYY-MM');
var eventArray = {{ data|tojson }};
var temp = [{
date: thisMonth + '-22',
type: 1
}, {
date: thisMonth + '-27',
type: 2
}, {
date: thisMonth + '-13',
type: 1
}];
calendars.clndr1 = $('.cal1').clndr({
events: eventArray,
targets: {
day: 'day',
},
clickEvents: {
click: function (target) {
console.log('Cal-1 clicked: ', target);
},
today: function () {
console.log('Cal-1 today');
},
nextMonth: function () {
console.log('Cal-1 next month');
},
previousMonth: function () {
console.log('Cal-1 previous month');
},
onMonthChange: function () {
console.log('Cal-1 month changed');
},
nextYear: function () {
console.log('Cal-1 next year');
},
previousYear: function () {
console.log('Cal-1 previous year');
},
onYearChange: function () {
console.log('Cal-1 year changed');
},
nextInterval: function () {
console.log('Cal-1 next interval');
},
previousInterval: function () {
console.log('Cal-1 previous interval');
},
onIntervalChange: function () {
console.log('Cal-1 interval changed');
}
},
multiDayEvents: {
singleDay: 'date',
endDate: 'endDate',
startDate: 'startDate'
},
showAdjacentMonths: true,
adjacentDaysChangeMonth: false
});
// Bind all clndrs to the left and right arrow keys
$(document).keydown(function (e) {
// Left arrow
if (e.keyCode == 37) {
calendars.clndr1.back();
calendars.clndr2.back();
calendars.clndr3.back();
}
// Right arrow
if (e.keyCode == 39) {
calendars.clndr1.forward();
calendars.clndr2.forward();
calendars.clndr3.forward();
}
});
});
I don't know your code, so I'm working with the test of CLNDR from github - folder "tests".
Add at the bottom of test.js (basically just make sure it's after clndr activation)
var thisMonth = moment().format('YYYY-MM');
var temp = [{
date: thisMonth + '-22',
type: 1
}, {
date: thisMonth + '-27',
type: 2
}, {
date: thisMonth + '-13',
type: 1
}];
for (event of temp) {
$('.calendar-day-' + event.date).addClass('ev-type-' + event.type);
};
Then add some css styles to test.html <head> just to clearly see it's working
.ev-type-1 {
background: #F00 !important;
color: #fff !important;
}
.ev-type-2 {
background: #0F0 !important;
color: #fff !important;
}

Javascript passing function as object affects scope

I am passing a function as a parameter and i am loosing scope of certain objects unless the object is in global scope. I want to remove the object from global scope.
Here aliasGrid is in global scope i would like to not have it global. However if i
remove its global scope i cannot access it in deleteAliasName() function under.
Global Scope Declaration
aliasGrid = new AliasGrid();
aliasGrid.initialize();
The issue is at showConfirmationDialog('deleteAliasName', 'noResponseConfirmationDialog',aliasNotificationLabel); i pass the name of two functions as string and they are then executable when the 'yes' and 'no' buttons are clicked on the ConfirmationDialog.
This works fine, however i would like the deleteAliasName() to be a property of the AliasGrid function and be passed as a paremeter on showConfirmationDialog('deleteAliasName', 'noResponseConfirmationDialog',aliasNotificationLabel); and executable when the 'yes' button of the ComfirmationDialog is clicked.
AliasGrid.js
function AliasGrid() {
var aliasData= [];
var aliasNotificationLabel = 'Alias Name';
return {
load: function(){
//create grid
},
add: function(){
//adds record to grid
},
getAliasData: function () {
return this.aliasData;
},
delete: function () {
try {
var aliasNameGrid = dijit.byId('aliasNameGrid');
var deleteAliasNameSelection = aliasNameGrid.selection;
var deleteAliasNameCount = 0;
for (var i in deleteAliasNameSelection) {
deleteAliasNameCount++; }
if (deleteAliasNameCount > 0) {
showConfirmationDialog('deleteAliasName', 'noResponseConfirmationDialog',aliasNotificationLabel);
} else {
showNotificationDialog('okResponseNotificationDialog', 'Select Record(s) For Deletion !', aliasNotificationLabel);
}
} catch (error) {
showNotificationDialog('okResponseNotificationDialog', error, aliasNotificationLabel);
}
}
};
};
Confirmation Dialog
function showConfirmationDialog(yesFunction, noFunction, title) {
var confirmationDialog = new dijit.Dialog({
id: 'deleteGridRecordConfirmationId',
title: "<img src='images/niblogo.png' alt='National Insurance Board'class='loginDialogLogo'/>" + title,
content: '<table style= "width: 300px;">' + '<tr>' + '<th style="text-align:center; padding: 5px" colspan="2"><label> Are Your Sure ? </label></th>' + '</tr>' +
'</table>' +
'<div class="dijitDialogPaneActionBar" style="text-align:center;"><button id= yesBtnId onclick=' + yesFunction + ' >Yes</button><button id=noBtnId onclick=' + noFunction + '("deleteGridRecordConfirmationId")>No</button></div>'
});
confirmationDialog.show();
}
DeleteAliasName
function deleteAliasName() {
try {
var aliasData = aliasGrid.getAliasData();
var aliasStore = new dojo.store.Observable(new dojo.store.Memory({
data: aliasData,
idProperty: "id"
}));
var grid = dijit.byId('aliasNameGrid');
aliasStore.query({}).forEach(function (AliasName) {
if (grid.selection[AliasName.id]) {
aliasStore.remove(AliasName.id);
}
});
function showConfirmationDialog(yesFunction, noFunction, title) {
var confirmationDialog = new dijit.Dialog({
id: 'deleteGridRecordConfirmationId',
title: "<img src='images/niblogo.png' alt='National Insurance Board'class='loginDialogLogo'/>" + title,
content: '<table style= "width: 300px;">' + '<tr>' + '<th style="text-align:center; padding: 5px" colspan="2"><label> Are Your Sure ? </label></th>' + '</tr>' +
'</table>' +
'<div class="dijitDialogPaneActionBar" style="text-align:center;"><button id="yesBtnId">Yes</button><button id="noBtnId">No</button></div>'
});
var dijitDialog = $("div.dijitDialogPaneActionBar");
dijitDialog.children("button#yesBtnId").click(yesFunction);
dijitDialog.children("button#noBtnId").click(function()
{
noFunction("deleteGridRecordConfirmationId");
});
confirmationDialog.show();
}
AliasGrid:
function AliasGrid()
{
var aliasData= [];
var aliasNotificationLabel = 'Alias Name';
var self = this;
self.deleteAliasName = function() {
try {
var aliasData = self.getAliasData();
var aliasStore = new dojo.store.Observable(new dojo.store.Memory({
data: aliasData,
idProperty: "id"
}));
var grid = dijit.byId('aliasNameGrid');
aliasStore.query({}).forEach(function (AliasName) {
if (grid.selection[AliasName.id]) {
aliasStore.remove(AliasName.id);
}
});
}
};
return {
load: function(){
//create grid
},
add: function(){
//adds record to grid
},
delete: function () {
try {
var aliasNameGrid = dijit.byId('aliasNameGrid');
var deleteAliasNameSelection = aliasNameGrid.selection;
var deleteAliasNameCount = 0;
for (var i in deleteAliasNameSelection) {
deleteAliasNameCount++; }
if (deleteAliasNameCount > 0) {
showConfirmationDialog(self.deleteAliasName, 'noResponseConfirmationDialog',aliasNotificationLabel);
} else {
showNotificationDialog(okResponseNotificationDialog, 'Select Record(s) For Deletion !', aliasNotificationLabel);
}
} catch (error) {
showNotificationDialog(okResponseNotificationDialog, error, aliasNotificationLabel);
}
}
};
};

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