variable being reset in a 'for loop' - javascript

I am pushing info from a database to a calendar, where each date has an id equal to an id in the database. The code iterates through the database searching for matching pairs. If a match is found, the name of the image is to be placed into image tags in the calendar. However, the default image is the only one showing, and the variable calImg is seemingly being reset to default. var idCalendar = [];
var arrayCalendar = -1;
var calImg; are global variables
while (counter <= numOfDays) {
var dateID = counter + monthIDName;
idCalendar[counter - 1] = dateID;
//alert(idCalendar[counter-1]);
// When to start new line.
if (weekdays2 > 6) {
weekdays2 = 0;
htmlContent += "</tr><tr>";
}
//check to ensure the mydb object has been created
/////////////////////////////////////////////////////////////////////////////
if (mydb) {
//Get all the entry from the database with a select statement
mydb.transaction(function(t) {
t.executeSql("SELECT rating FROM entry WHERE calendar=?", [idCalendar[arrayCalendar + 1]], function(t, results) {
var i;
//Iterate through the results
if (results.rows.length != 0) {
for (i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
calImg = row.rating;
alert(idCalendar[arrayCalendar] + calImg);
}
} else {
alert(idCalendar[arrayCalendar]);
calImg = 'default';
}
});
arrayCalendar++;
});
} else {
myApp.alert("query error");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// if counter is current day.
// highlight current day using the CSS defined in header.
if (counter == day && month == curMonth && year == curYear) {
htmlContent += "<td class='dayNow' id='" + counter + monthIDName + "' onMouseOver='this.style.background=\"#FF0000\"; this.style.color=\"#FFFFFF\"' " + "onMouseOut='this.style.background=\"#FFFFFF\"; this.style.color=\"#FF0000\"'>" + counter + "<img src= 'img/" + calImg + ".png' align='left' height= '15' width= '15'>" + "<br>" + "</td>";
} else {
htmlContent += "<td class='monthNow' id='" + counter + monthIDName + "' onMouseOver='this.style.background=\"#FF0000\"'" + " onMouseOut='this.style.background=\"#FFFFFF\"'>" + counter + "<img src= 'img/" + calImg + ".png' align='left' height= '15' width= '15'>" + "<br>" + "</td>";
}
weekdays2++;
counter++;
}

Related

how to find the divs specific Nth siblings of child divs positions

i create new hours calendar. as per the IMAGE1 when user click on any of div that dynamic Span was created up to 8 hours.
i.e. if click on 00:00 its design up to 08:00 hours
so my question is how to get that specific siblings 8th divs child position.
Or any other way please suggest me.
$(this).eq(+8).attr("id");
IMAGE1
Table Design Code when ajax return Success:
$(r.emp_nm).each(function (index) {
tabelBody += "<tr><td style='width:10%'><div class='col-xs-3 col-md-3 on-break-tab'>" + this.fname.charAt(0) + this.lname.charAt(0) + "</div>" + this.fname + ' ' + this.lname + " </td>";
for (var i = 0; i < 24; i++) {
var tabelsubBody = "";
var p = 15;
var t_id = r.hours[i];
for (var j = 0; j < 4; j++) {
tabelsubBody += "<div style='float:left; width:25%;height:inherit;' class='Dropablesub_td' data-employeID='" + this.id + "' data-date='" + t_id + "' id='" + t_id + "_" + this.id + "_" + j + "'></div>";
}
if (i === 23) {
tabelBody += "<td style='width:12.5%' class='Dropabletd' data-employeID='" + this.id + "' data-date='" + t_id + "' id='" + t_id + "_" + this.id + "'>" + tabelsubBody + "</td></tr>";
} else {
tabelBody += "<td style='width:12.5%' class='Dropabletd' data-employeID='" + this.id + "' data-date='" + t_id + "' id='" + t_id + "_" + this.id + "'>" + tabelsubBody + "</td>";
}
}
});
$("#tabelBody").html(tabelBody);
$("#tdDate").html(r.today);
$("#SelectDate").val(r.today);
$("#currentSelect").val("Days");
Events();
And Events() is :
function Events() {
$("body").on("click", ".Dropablesub_td", function () {
var hidid = $(this).attr("id");
var Myleft = $(this).position().left;
var Mytop = $(this).position().top;
alert($(this).eq(+8).attr("id"));
$(this).append("<span id='" + hidid + "' class='divId label label-success ui-widget-content filediv unselectable' >ABCDEFGHIJKLMNOPQRSTUVWXYZ<span>");
$(this).children(
).css({zIndex: 999, position: "absolute", top: Mytop, left: Myleft, width: '40%', display: "block", border: "#808080 solid 2px", color: "black", background: "#00CEB4"});
});
}
You can get the desired element using .index() of current element and then using .eq() to target the next element.
Here in the snippet I have created a pseudo code for demonstration
$(document).on("click", ".dropabletd", function() {
var tr = $(this).closest('tr');
var tds = tr.find('td');
var index = tds.index(this);
var sibling = tds.eq(index + 8);
console.log($(this).attr('id'), sibling.attr('id'));
});
createTable();
function createTable() {
var tabelBody = ""
for (var i = 0; i <= 23; i++) {
tabelBody += "<td class='dropabletd' id='id" + i + "'>" + i + "</td>";
}
$("table tr").html(tabelBody);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr></tr>
</table>

How to fire the javascript function in the textboxes that are getting created dynamically in asp .net

Below is my code which creates the textboxes dynamically in modal pop up each time when i click add button and removes the text boxes in that row each time when i click remove button which is working fine till here the problem is i have the javascript function which validates the month date and year in text box that if if we give any number greater than 12 it shows message that month should be less than 12 similarly for date also it will accept till 31 but if it is greater than 31 it shows error message and similarly year also but this is done for our asp text boxes how can i make this javascript function to work in modal pop where the textboxes are created dynamically
<script type="text/javascript">
function GetDynamicTextBox(value) {
if (value == "") {
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + value + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
//Min = "";
// Hours = "";
//
}
}
var HHEdit = "";
var MMEdit = "";
function GetDynamicTextBox1(value) {
values = value.split(' ');
one = values[0];
two = values[1];
values = two.split(':');
three = values[0];
Four = values[1];
HHEdit = three;
MMEdit = Four;
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + one + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
// $('.DynamicTextBox').val(one);
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function AddTextBox1() {
var inputCount = document.getElementById('TextBoxContainer').getElementsByTagName('input').length;
if (inputCount == "0") {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox1(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
var Hours = "";
var Min = "";
function FillDropdown() {
for (var i = 0; i < 24; i++) {
if (i >= 0 && i <= 9) {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>'
}
else {
Hours += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Hours += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
for (var i = 0; i < 60; i++) {
if (i >= 0 && i <= 9) {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
//$('#Item').append(option);
}
window.onload = RecreateDynamicTextboxes;
</script>
Code for date month year validation using javascript
var fdate = document.getElementById('<%=txtFromDate.ClientID%>').value;
var tdate = document.getElementById('<%=txtToDate.ClientID%>').value;
var fromdate = fdate.split('/');
var fmonth = fromdate[0];
var fdate = fromdate[1];
var fyear = fromdate[2];
if (fmonth > 12) {
message += "From Month Should Be Less Than 12." + "\n";
}
if (fdate > 31) {
message += "From Date Cannot Be Greater Than 31." + "\n";
}
if (fyear < 2000 || fyear > 2030) {
message += "From Year Should Be In Between 2000 to 2030." + "\n";
}
var todate = tdate.split('/');
var tmonth = todate[0];
var tdate = todate[1];
var tyear = todate[2];
if (tmonth > 12) {
message += "To Month Should Be Less Than 12." + "\n";
}
if (tdate > 31) {
message += "To Date Cannot Be Greater Than 31." + "\n";
}
if (tyear < 2000 || tyear > 2030) {
message += "To Year Should Be In Between 2000 to 2030."+"\n";
}
if (message != "") {
alert(message);
return false;
}
From Date: <asp:TextBox ID="txtFromDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox> <span id="error" style="color: Red; display: none">* Invalid Character</span>
To Date: <asp:TextBox ID="txtToDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox><span id="Span1" style="color: Red; display: none">* Invalid Character</span>
I don't see that you've actually defined your IsValidData function. I'm assuming that you've done that somewhere...
You can pass this to your IsValidData function as a parameter to work with the element that triggered the event in your function..
Also you should try moving away from inline functions to event listeners. This stack post (JavaScript click event listener on class) talks about applying an event listener to a class of DOM elements.
If you are using jQuery, since you included this tag, then I'd encourage you to look into the jQuery .on() function to add event handlers. It'll make everything much easier (http://api.jquery.com/on/)
If you do not know what a javascript event listener is, then start here (https://www.w3schools.com/js/js_htmldom_eventlistener.asp)

Change position of data in tables

I have written JavaScript which retrieves data and sets it into a series of tables as shown below.
$(function()
{
$.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'9BBF789F-E5BA-449D-A595-BAA326E2C8FF')/Items?$expand=Category&$select=Id,Related_x0020_Working_x0020_PracId,Title,Reference,Policy_x0020_Type,Category/Title&$orderby=Category/Title asc",
type:"get",
headers: { "accept": "application/json;odata=verbose" },
success: function(dataObj)
{
//to uniquely identifiy the accordion.
var intCat = 0;
var arrPolicies = [];
var arrCategories = [];
//Get the policies and seperate out the categories from the returned REST call
for(var i =0; i < dataObj.d.results.length; i++)
{
var strCategory = dataObj.d.results[i].Category.Title;
arrPolicies.push({
"Id" : dataObj.d.results[i].Id,
"Title" : dataObj.d.results[i].Title,
"Category" : strCategory,
"Ref" : dataObj.d.results[i].Reference,
"PolicyType" : dataObj.d.results[i].Policy_x0020_Type,
"WorkingPracticeId" : dataObj.d.results[i].Related_x0020_Working_x0020_PracId
});
//setting category if not found
//in array
if(arrCategories.indexOf(strCategory) == -1)
{
//Add the category to the list...
arrCategories.push(strCategory);
}
}
//Output the menu to the screen for each category - one by one
arrCategories.forEach(function(varCategory)
{
var strCatIdentifier = "tblCategory_" + intCat;
var strCatImgIdentifier = "tblCategory_image_" + intCat;
var strCategoryInfo = "<table>"+
"<tbody>" +
"<tr>"+
"<td class='category'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatIdentifier + ","+strCatImgIdentifier+")'>"+
"<img id='"+strCatImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand category'/>"+
"</a> "+
varCategory +
"</td>"+
"</tr>"+
"<tr><td>"+
"<table id='" + strCatIdentifier + "' class='indent hidden'>";
//looping through policies - add the details into the category table's cell
arrPolicies.forEach(function(varPolicy)
{
//checking the category attached to the policy is the same as what
//category it is on
if(varPolicy.Category == varCategory)
{
//checking to see if the
if(varPolicy.PolicyType == "Policy and Responsibility")
{
strCategoryInfo += "<tr>"+
"<td class='policy'>" +
"<a href='#'>"+
"<img src='"+_spPageContextInfo.webAbsoluteUrl+"/SiteAssets/Images/arrowicon.png' alt='View Document'/>"+
"</a>"
+ varPolicy.PolicyType + ": "+varPolicy.Ref +" - " + varPolicy.Title +
"</td>"+
"</tr>";
}
//If Working Practice - add in the sub-table (3rd level table) for attachments
if(varPolicy.PolicyType == "Working Practices")
{
var strCatWPIdentifier = "tblWorkingPractice" + varPolicy.Id;
var strCatWPImgIdentifier = "sub_level_image" + varPolicy.Id;
strCategoryInfo += "<tr>"+
"<td class='working_practice'>"+
"<a href='javascript:ExpandCollapseRow(" + strCatWPIdentifier + ","+strCatWPImgIdentifier+")'>"+
"<img id='"+strCatWPImgIdentifier+"' src='" + _spPageContextInfo.webAbsoluteUrl + "/SiteAssets/Images/expand-16.png' alt='expand working practice'/>"+
"</a> "+
varPolicy.PolicyType + " - " + varPolicy.Title+
"</td>"+
"</tr>";
var intAttachmentCount = 0;
//Build a table by looping through the policies array AGAIN and only use the policies where the Policy Type is 'Attachment' AND the 'WorkingPracticeID' is the same as the pilocy ID
arrPolicies.forEach(function(varWPAttachment)
{
if(varWPAttachment.WorkingPracticeId == varPolicy.Id && varWPAttachment.PolicyType == "Working Practice Attachment")
{
intAttachmentCount++;
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
varWPAttachment.PolicyType +" - "+ varWPAttachment.Title+ " - " + varPolicy.Title+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
});
if(intAttachmentCount == 0)
{
strCategoryInfo += "<tr>"+
"<td>"+
"<table id='"+strCatWPIdentifier+"' class='indent hidden'>"+
"<tr>"+
"<td>"+
"Sorry, no attachments found for this practice."+
"</td>"+
"</tr>"+
"</table>"+
"</td>"+
"</tr>";
}
}
}
});
//Close the 'Category details' table
strCategoryInfo += "</table>";
//Close the table for the category...
strCategoryInfo += "</td></tr>" +
"</tbody>"+
"</table>";
intCat++;
$('#divQualityFrameworkMenu').append(strCategoryInfo + "<br />");
});
},
error: function(error)
{
alert("Error");
}
});
});
I want to be able to organise them so that related data is grouped together ie Policies are above working practices.
How would I go about doing this
This seems pretty easy. After the first for (var d = 0; [...] ) loop, but before the arrCategories.forEach([...]), just sort arrPolicies to your choosing:
arrPolicies.sort(function(policy1, policy2) {
//Policies BEFORE Working Practicies:
if (policy1.PolicyType === "Policies and Responsibilities" && policy2.PolicyType === "Working Practices") {
return -1;
}
//Working Practicies AFTER Policies:
if (policy1.PolicyType === "Working Practices" && policy2.PolicyType === "Policies and Responsibilities") {
return 1;
}
//[Include any other orderings you might have...]
//If you've reached the end here, then you must not care about the ordering of these policies, so just make them "equal":
return 0;
});

Referencing an array item in a function (as string) javascript

I created an array of strings, with the format "monthX" where is a number that increases throughout the array.
I have a function where I'm trying to reference a specific item of the array, but it keeps coming in as undefined. Here's my code:
function listCategories() {
categoryList.innerHTML = ""
for (var propertyName in categoryObject) {
var rowHTML = "<div>"
rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
rowHTML += "</div>"
categoryList.innerHTML += rowHTML
}
}
//Months to load in
for (var i=0; i<24; i++) {
monthList[i] = "month" + (i + startingMonth)
}
The area I'm interested in is that "monthList[3]" line. That keeps coming in as undefined, even though I console.log(monthList[3]) it correctly says "month6". Any ideas? Do I have bug in my code?
Well, two questions:
WHEN do you call "listCategories()" ?
before or after you set monthList?
And, have you set the global for monthList first?
//globalize monthList array to be usable in functions
var monthList;
function listCategories() {
categoryList.innerHTML = ""
for (var propertyName in categoryObject) {
var rowHTML = "<div>"
rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
rowHTML += "</div>"
categoryList.innerHTML += rowHTML
}
}
//Months to load in
for (var i=0; i<24; i++) {
monthList[i] = "month" + (i + startingMonth)
}
//do NOT CALL listCategories prior this line!!
That should do
In the code you show us, you never declare monthList or define it as an array.
function listCategories() {
categoryList.innerHTML = ""
for (var propertyName in categoryObject) {
var rowHTML = "<div>"
rowHTML += "<span class = 'category'>" + categoryObject[propertyName].name + "</span>"
rowHTML += "<span class = '" + monthList[3] + "'><input/></span>"
rowHTML += "</div>"
categoryList.innerHTML += rowHTML
}
}
var monthList = [],
startingMonth = 1;
//Months to load in
for (var i=0; i<24; i++) {
monthList[i] = "month" + (i + startingMonth)
}
Notice the additional lines I added after the function definition, but before the loop.

Fix incorrect nesting

function drawinventoryList() {
inventoryArray.sort();
var inventoryString = "";
for (x in inventoryArray) {
arrayValue = inventoryArray[x];
var counter = parseInt(x) + 1;
if (counter == 1) {
inventoryString = "<table width='100%' celpadding='0' cellspacing='0' style='border:1px solid #d00;'>"
}
if (arrayValue.substring(0, arrayValue.indexOf("#")) != "XXXXXXXX") {
inventoryString = inventoryString + "<tr><td>" + counter + ". " + arrayValue.substring(0, arrayValue.indexOf("#")) + ", " + arrayValue.substring(arrayValue.indexOf("#") + 1) + " (remove)</td></tr>";
}
}
if (inventoryString == "") inventoryString = "None."
document.getElementById("selectedInventories").innerHTML = inventoryString;
}
... this function creates an invalid table. I need the 'counter' 'name' and 'remove link' in separate columns. How do I correctly create and close all tags?
Many thanks
It looks like you're just forgetting the closing tag for the table. Try this instead:
function drawinventoryList() {
inventoryArray.sort();
var inventoryString = "";
for (x in inventoryArray) {
arrayValue = inventoryArray[x];
var counter = parseInt(x) + 1;
if (counter == 1) {
inventoryString = "<table width='100%' celpadding='0' cellspacing='0' style='border:1px solid #d00;'>"
}
if (arrayValue.substring(0, arrayValue.indexOf("#")) != "XXXXXXXX") {
inventoryString = inventoryString + "<tr><td>" + counter + ". " + arrayValue.substring(0, arrayValue.indexOf("#")) + ", " + arrayValue.substring(arrayValue.indexOf("#") + 1) + " (remove)</td></tr>";
}
}
if (inventoryString == "") {
inventoryString = "None.";
} else {
inventoryString = inventoryString + "</table>";
}
document.getElementById("selectedInventories").innerHTML = inventoryString;
}
The only change was from:
if (inventoryString == "") inventoryString = "None."
to:
if (inventoryString == "") {
inventoryString = "None.";
} else {
inventoryString = inventoryString + "</table>";
}
Update: In your comment, you stated that
I still need to separate counter, name and link in separated [sic] TD
That's probably just a matter of inserting some </td><td> sections, something like:
inventoryString = inventoryString +
"<tr>" +
"<td>" + counter + ".</td>" +
"<td>" + arrayValue.substring(0, arrayValue.indexOf("#")) + ", " +
arrayValue.substring(arrayValue.indexOf("#") + 1) + "</td>" +
"<td>(<a href=\"javascript:removeinventory('" + x +
"')\">remove</a>)</td>" +
"</tr>";
I am not entirely sure what you are trying to do but maybe this might be what you are looking for.
function drawinventoryList() {
inventoryArray.sort();
var inventoryString = "<table width='100%' celpadding='0' cellspacing='0' style='border:1px solid #d00;'>";
var count = 0;
for (x in inventoryArray) {
arrayValue = inventoryArray[x];
count++;
if (arrayValue.substring(0, arrayValue.indexOf("#")) != "XXXXXXXX") {
inventoryString = inventoryString + "<tr><td>" + counter + ". " + arrayValue.substring(0, arrayValue.indexOf("#")) + ", " + arrayValue.substring(arrayValue.indexOf("#") + 1) + " (remove)</td></tr>";
}
}
if (count == 0) {
inventoryString = "None.";
} else {
inventoryString = inventoryString + "</table>";
}
document.getElementById("selectedInventories").innerHTML = inventoryString;
}

Categories