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++;
}
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>
I have a dynamic add/delete row functionality in the struts2 application.
Now the first value is properly bound from JSP to action since the first value exists with struts tags (s:select) in the JSP, but the dynamic rows added from the Javascript are not getting bind to the Action list. The action ArrayList values are not bound, this is the code I have so far:
<legend class="legendtitle">Training Needs Analysis</legend>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="trainingTable">
<thead>
<tr>
<td class="Htd_one1">
<div align="center">Course:</div>
</td>
<td class="Htd_one1">
<div align="center">Course Name (if Others):<span class="mandatory">*</span></div>
</td>
<td class="Htd_one1">
<div align="center">Training Type:<span class="mandatory">*</span></div>
</td>
<td class="Htd_one1">
<div align="center">Reason For Recommendation:<span class="mandatory">*</span></div>
</td>
<td class="Htd_one1">
<div align="center">Action</div>
</td>
</tr>
</thead>
<tbody>
<tr>
<td class="dataone1" width="20%">
<s:div align="center">
<s:select list="courseNameList" name="appTrngMstrList[0].courseCode" headerKey="0" headerValue="SELECT" id="courseCode0"
onchange="enableDetailCourseSection(this.value,0)" theme="simple" listKey="displayKey" cssClass="txtbox"
listValue="displayValue" />
</s:div>
</td>
<s:hidden name="hrAppHeader.appHidenVarTrngMstrList[0].courseCode" id="courseCodeHide0"></s:hidden>
<td class="dataone1">
<s:div id="courseOthersTextTd" align="center">
<s:textfield id="courseOthers0" name="appTrngMstrList[0].courseOthers" cssClass="txtbox_mandatory" theme="simple" cols="50"
rows="3" maxLength="200" onblur="convertToUpper(this)" />
</s:div>
</td>
<s:hidden name="hrAppHeader.appHidenVarTrngMstrList[0].courseOthers" id="courseOthersHide0"></s:hidden>
<td class="dataone1">
<s:div id="trainingTypeTextTd" align="center">
<s:select headerKey="0" headerValue="SELECT" list="#{'I':'INTERNAL','E':'EXTERNAL'}" name="appTrngMstrList[0].trainingType"
id="trainingType0" theme="simple" cssClass="txtbox_mandatory"></s:select>
</s:div>
</td>
<s:hidden name="hrAppHeader.appHidenVarTrngMstrList[0].trainingType" id="trainingTypeHide0"></s:hidden>
<td class="dataone2">
<s:div align="center">
<s:textarea name="appTrngMstrList[0].reasonOfRecomndtn" id="reasonOfRecomndtn0" cols="40" theme="simple" cssClass="txtbox_mandatory_big"
onblur="convertToUpper(this);" onkeydown="textCounter(this,4000);" onkeyup="textCounter(this,4000);"
/>
</s:div>
<s:hidden name="hrAppHeader.appHidenVarTrngMstrList[0].reasonOfRecomndtn" id="reasonOfRecomndtnHide0"></s:hidden>
</td>
<td align="center">
<input type="button" value="Delete" class="btn" id="deletSelfrowid" onclick="deleteTrainingRow(0);" />
</td>
</tr>
</tbody>
</table>
<table id="table1" width="100%">
<tr>
<td colspan="3" align="center">
<input type="button" class="btn" value="Add Row" id="addSelfrowId" onclick="addTrainingRow(0)">
</td>
</tr>
</table>
Javascript Code
function addTrainingRow(index) {
var str = "";
var rowCnt = document.getElementById('rowCnt').value;
var tbody =
document.getElementById("trainingTable").getElementsByTagName("TBODY")[0];
var row = document.createElement("TR");
var check = rowCnt % 2;
if (check == 0) {
row.className = "oddrow";
}
else {
row.className = "evenrow";
}
var optionValue1 = new Array();
var keyValue1 = new Array();
var courseCode = document.getElementById('courseCode' + index);
var length1 = courseCode.options.length;
for (var i = 0; i < length1; i++) {
dropdownKey = courseCode.options[i].value;
keyValue1[i] = dropdownKey;
}
for (var i = 0; i < length1; i++) {
dropdownValues = courseCode.options[i].text;
optionValue1[i] = dropdownValues;
}
var optionValue2 = new Array();
var keyValue2 = new Array();
var strVal = "";
strVal = strVal + '<option value=\"0">SELECT</option><option value=\"I\">INTERNAL</option><option value=\"E\">EXTERNAL</option>';
var s1 = "";
var s2 = "";
for (var i = 0; i < optionValue1.length; i++) {
s1 = s1 + '<option value="' + keyValue1[i] + '">' + optionValue1[i] + '</option>';
}
s2 = s2 + '<option value="0">SELECT</option>';
//var str1='<div align=\"center\"><select class=\"txtbox\" theme=\"simple\" id=\"courseCode'+rowCnt+'\" name=\"appTrngMstrList['+rowCnt+'].courseCode\" onchange=\"enableDetailCourseSection(this.value,'+rowCnt+');\">'+s1+'</select></div>';
var str1 = '<div align=\"center\"><select class=\"txtbox\" theme=\"simple\" id=\"courseCode' + rowCnt + '\" name=\"appTrngMstrList[' + rowCnt + '].courseCode\" onchange=\"enableDetailCourseSection(this.value,' + rowCnt + ');\">' + s1 + '</select></div><input type=\"hidden\" name=\"hrAppHeader.appHidenVarTrngMstrList[' + rowCnt + '].courseCode\" id=\"courseCodeHide' + rowCnt + '\"/>';
var str4 = '<div align=\"center\"><input type=\"text\" name=\"appTrngMstrList[' + rowCnt + '].courseOthers\" id=\"courseOthers' + rowCnt + '\" class=\"txtbox_mandatory\" theme=\"simple\" cols=\"50\" rows=\"3\" maxLength=\"200\" onblur=\"convertToUpper(this)\"/></div><input type=\"hidden\" name=\"hrAppHeader.appHidenVarTrngMstrList[' + rowCnt + '].courseOthers\" id=\"courseOthersHide' + rowCnt + '\"/>';
var str2 = '<div id=\"trainingTypeTextTd' + rowCnt + '\" align=\"center\"><select class=\"txtbox_mandatory\" theme=\"simple\" id=\"trainingType' + rowCnt + '\" name=\"appTrngMstrList[' + rowCnt + '].trainingType\">' + strVal + '</select></div><input type=\"hidden\" name=\"hrAppHeader.appHidenVarTrngMstrList[' + rowCnt + '].trainingType\" id=\"trainingTypeHide' + rowCnt + '\"/>';
var str5 = '<div align=\"center\"><input type=\"text\" theme=\"simple\" class=\"txtbox_mandatory_big\" cols=\"40\" name=\"appTrngMstrList[' + rowCnt + '].reasonOfRecomndtn\" id=\"reasonOfRecomndtn' + rowCnt + '\" onblur=\"convertToUpper(this);\" onkeydown=\"textCounter(this,4000);\" onkeyup=\"textCounter(this,4000);\"/></div><input type=\"hidden\" name=\"hrAppHeader.appHidenVarTrngMstrList[' + rowCnt + '].reasonOfRecomndtn\" id=\"reasonOfRecomndtnHide' + rowCnt + '\"/>';
var str8 = '<div align=\"center\"><input type=\"button\" value=\"Delete\" class=\"btn\" id=\"deletSelfrowid\" onclick=\"deleteTrainingRow(' + rowCnt + ');\"/></div>';
var td1 = document.createElement("TD");
td1.innerHTML = str1;
var td4 = document.createElement("TD");
td4.innerHTML = str4;
var td2 = document.createElement("TD");
td2.innerHTML = str2;
var td5 = document.createElement("TD");
td5.innerHTML = str5;
var td8 = document.createElement("TD");
td8.innerHTML = str8;
td1.className = "td_one1";
td4.className = "td_one1";
td2.className = "td_one1";
td5.className = "td_one1";
td8.className = "td_one1";
row.appendChild(td1);
row.appendChild(td4);
row.appendChild(td2);
row.appendChild(td5);
row.appendChild(td8);
tbody.appendChild(row);
//set the number of rows
document.getElementById("rowCnt").value = Number(rowCnt) + 1;
}
function deleteTrainingRow(id) {
var optionValue1 = new Array();
var optionValue2 = new Array();
var keyValue1 = new Array();
var keyValue2 = new Array();
//Get the existing number of rows
var existingNumOfRows = document.getElementById("rowCnt").value;
var atLeastOneRowSelected = false;
// TO check atleast one row is not deleted.
var count = 0;
if (parseInt(existingNumOfRows) == 1) {
alert("Cannot delete all rows.");
return false;
}
var index = 1;
var rowCnt = 0;
var recommendStr = '';
var otherStr = '';
var tempArray = new Array();//This will be used to take the backup of the current unselected rows
for (var i = 0; i < existingNumOfRows; i++) {
if (parseInt(id) != parseInt(i)) {
var row = document.createElement("TR");
var check = rowCnt % 2;
if (check == 0) {
row.className = "oddrow";
}
else {
row.className = "evenrow";
}
var courseCode = document.getElementById('courseCode' + i);
var length1 = courseCode.options.length;
for (var j = 0; j < length1; j++) {
dropdownKey = courseCode.options[j].value;
keyValue1[j] = dropdownKey;
}
for (var j = 0; j < length1; j++) {
dropdownValues = courseCode.options[j].text;
optionValue1[j] = dropdownValues;
}
var s1 = "";
for (var j = 0; j < optionValue1.length; j++) {
if (document.getElementById("courseCode" + i).selectedIndex == j) {
s1 = s1 + '<option value="' + keyValue1[j] + '" selected>' + optionValue1[j] + '</option>';
}
else {
s1 = s1 + '<option value="' + keyValue1[j] + '">' + optionValue1[j] + '</option>';
}
}
var trainingType = document.getElementById('trainingType' + i);
var length2 = trainingType.options.length;
for (var j = 0; j < length2; j++) {
dropdownKey = trainingType.options[j].value;
keyValue2[j] = dropdownKey;
}
for (var j = 0; j < length2; j++) {
dropdownValues = trainingType.options[j].text;
optionValue2[j] = dropdownValues;
}
var s2 = "";
for (var j = 0; j < optionValue2.length; j++) {
if (document.getElementById("trainingType" + i).selectedIndex == j) {
s2 = s2 + '<option value="' + keyValue2[j] + '" selected>' + optionValue2[j] + '</option>';
}
else {
s2 = s2 + '<option value="' + keyValue2[j] + '">' + optionValue2[j] + '</option>';
}
}
recommendStr = document.getElementById('reasonOfRecomndtn' + i).value;
//alert(document.getElementById("courseCode"+i).selectedIndex);
if (document.getElementById("courseCode" + i).selectedIndex == "20") {
otherStr = document.getElementById('courseOthers' + i).value;
}
var str1 = '<div align=\"center\"><select class=\"txtbox\" theme=\"simple\" id=\"courseCode' + rowCnt + '\" name="\appTrngMstrList[' + rowCnt + '].courseCode\" onchange=\"enableDetailCourseSection(this.value,' + rowCnt + ');\">' + s1 + '</select></div>';
var str4 = '<div align=\"center\"><input type=\"text\" name=\"appTrngMstrList[' + rowCnt + '].courseOthers\" id=\"courseOthers' + rowCnt + '\" class=\"txtbox_mandatory\" theme=\"simple\" cols=\"50\" rows=\"3"\ maxLength=\"200\" onblur=\"convertToUpper(this);\" value=\"' + otherStr + '\"/></div>';
var str2 = '<div id=\"trainingTypeTextTd' + rowCnt + '\" align=\"center\"><select class=\"txtbox_mandatory\" theme=\"simple\" id=\"trainingType' + rowCnt + '\" name=\"appTrngMstrList[' + rowCnt + '].trainingType\">' + s2 + '</select></div>';
var str5 = '<div align=\"center\"><input type=\"text\" theme=\"simple\" class=\"txtbox_mandatory_big\" cols=\"40\" name=\"appTrngMstrList[' + rowCnt + '].reasonOfRecomndtn\" id=\"reasonOfRecomndtn' + rowCnt + '\" onblur=\"convertToUpper(this);\" onkeydown=\"textCounter(this,4000);\" onkeyup=\"textCounter(this,4000);\" value=\"' + recommendStr + '\"/></div>';
var str8 = '<div align=\"center\"><input type=\"button\" value=\"Delete\" class=\"btn\" id=\"deletSelfrowid\" onclick=\"deleteTrainingRow(' + rowCnt + ');\"/></div>';
var td1 = document.createElement("TD");
td1.innerHTML = str1;
var td4 = document.createElement("TD");
td4.innerHTML = str4;
var td2 = document.createElement("TD");
td2.innerHTML = str2;
var td5 = document.createElement("TD");
td5.innerHTML = str5;
var td8 = document.createElement("TD");
td8.innerHTML = str8;
td1.className = "td_one1";
td4.className = "td_one1";
td2.className = "td_one1";
td5.className = "td_one1";
td8.className = "td_one1";
row.appendChild(td1);
row.appendChild(td4);
row.appendChild(td2);
row.appendChild(td5);
row.appendChild(td8);
tempArray[rowCnt] = row;
index++;
rowCnt++;
}
}
//Delete all the rows
var table = document.getElementById("trainingTable");
var headerRowCount = 0;
for (var i = (existingNumOfRows); i > headerRowCount; i--) {
table.deleteRow(i);
}
var tbody = document.getElementById("trainingTable").getElementsByTagName("TBODY")[0];
//Add the backup rows
for (var i = 0; i < rowCnt; i++) {
tbody.appendChild(tempArray[i]);
}
//set the number of rows
document.getElementById("rowCnt").value = Number(rowCnt);
}
I have all the getters/setters there in the POJO class, but still the appTrngMstrList[0] value, I get in the Action class, but whatever rows I add dynamically appTrngMstrList[1] does not get bind to the Action List.
Also, I put hidden variables as a workaround, but even the hrAppHeader.appHidenVarTrngMstrList does not bind dynamic rows.
I could not fully understand your code approach. But I am trying to answer in general. Hope this will help
If you are adding/removing elements on your JSP using javascript use same name for element and different Id.
<input name="firstInput" id="1'+rowIndex+'" />
On Your action class you will have something like
private String firstInput[];
//getter and setter
Once you submit your form, firstInput array will have value of all element with name firstInput
I am having trouble with a checkbox, that when clicked toggles an attribute of my "contact" object from 0 to 1.
The checkbox is part of a DIV that is generated containing all the object details.
The attribute i want to toggle is called "toggled".
What I was trying to achieve, was that when the checkbox is clicked, it executes the UpdateStatus() method with the "ID" of the object passed in as a parameter. Then loop through all the objects in the array to match the "ID" of the object.
The problem is it toggles every objects "toggled" attribute, not just the one im trying to target.
The Code that generates the div with the checkbox
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
var mapLocation = " ";
myControls.push(control);
if(this.daysUntil<=14){ //This checks to see if the contacts birthday is within 7 days or less,and creates a warning flag variable so we can display a warning flag
birthdayFlag = "<img src=resources/birthday.png>"
}else{
birthdayFlag = " "
};
if(this.post){ // this checks to see if there is a value in the Postcode attribute, if not it will set the map location to the address entered
mapLocation = this.post;
}else{
mapLocation = this.address;
}
var childDiv =
"<div class='parentDiv'>" +
this.firstName + " " + this.surname + " " + birthdayFlag + "<input type='checkbox' onclick='updateStatus(this.ID)'>" + " " + "<button class='btnForDiv' id='" + buttonid + "'" + " > Click to Expand </button>" +
"<div class='childDiv' id='" + divid + "' " + ">" + "<img class=map src='http://maps.google.com/maps/api/staticmap?scale=1¢er=" + mapLocation + "&zoom=14&size=500x350&maptype=hybrid&markers=size:normal|color:RED|label:C|" + mapLocation + "&sensor=false' style='float: right;border-style:groove'>" +
" " + "<span style='color:#5f9ea0';> Surname: </span>" + "<br>     " + this.surname +
"<BR>  " + "<span style='color:#5f9ea0';> First Name:</span> " +"<br>     " + this.firstName +
"<br>  " + "<span style='color:#5f9ea0';> Date Of Birth:</span> " +"<br>     " + this.days + "/" + this.months + "/" + this.years +
"<br>  " + "<span style='color:#5f9ea0';> Telephone Number:</span> " +"<br>     " + this.phone +
"<br>  " + "<span style='color:#5f9ea0';> Address:</span> " +"<br>     " + this.address + " " + this.post +
"<br>  " + "<span style='color:#5f9ea0';> Email Address:</span> " +"<br>     " + this.email +
"<br>  " + "<span style='color:#5f9ea0';> Group:</span> " +"<br>     " + this.group +
"<br>  " + "<span style='color:#5f9ea0';> Days Until Birthday:</span> " +"<br>     " + this.daysUntil +
"</div>" + "</div>" + "<HR width=1000px>" + "<BR> ";
return childDiv;
The code that is supposed to toggle the "toggled" attribute
var updateStatus = function(thisID){
alert("firing");
for (i = 0; i < contacts.length; i += 1) {
if (thisID = contacts[i].ID){
if (contacts[i].toggled = "0"){
contacts[i].toggled = "1";
}else{
if (contacts[i].toggled = "1"){
contacts[i].toggled = "0";
}
}
}
}
}
And the entire code incase it is required
var surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ; //Declaring variables for the fields
var Contact = function(surname,firstName,date, phone , address , post, email, group, imglink){
this.surname = surname ;
this.firstName = firstName ;
this.birthdayDate = new Date (date) ;
this.phone = phone;
this.address= address;
this.email = email;
this.post = post;
this.group = group;
this.toggled = "0" ;
this.ID = "";
}
var contacts = [];
upcomingBirthdays = [];
divid = 0;
buttonid = 1000;
mapid = 100;
myControls = [];
var getDate = function() {
for (var i= 0, j=contacts.length;i<j;i++){
var y = contacts[i].birthdayDate.getFullYear();
var m = contacts[i].birthdayDate.getMonth();
var d = contacts[i].birthdayDate.getDate();
contacts[i].days = d;
contacts[i].months = m + 1;
contacts[i].years = y ;
var today = new Date() ;
var ty = today.getFullYear();
contacts[i].bdThisYear = new Date(ty,m,d, 0 , 0 , 0);
}
}
var daysUntilBirthday = function(){
for (var i= 0, j=contacts.length;i<j;i++){
var today = new Date() ;
contacts[i].daysUntil = Math.round((contacts[i].bdThisYear - today ) /1000/60/60/24+1);
if (contacts[i].daysUntil <= 0){
contacts[i].daysUntil = contacts[i].daysUntil + 365 ;
}
}
}
var birthdayCheck = function(){
for (var i= 0, j=contacts.length;i<j;i++){
birth = "\n" + contacts[i].firstName + " " + contacts[i].surname + " has a birthday in " + contacts[i].daysUntil + " days" ;
if(contacts[i].daysUntil <= 14){
upcomingBirthdays.push (birth);
}
}
if(upcomingBirthdays.length > 0){
alert(upcomingBirthdays);
}
}
Contact.prototype.generateDiv = function(){
divid = divid + 1;
buttonid = buttonid + 1;
var control = [];
control[0] = divid;
control[1] = buttonid;
var mapLocation = " ";
myControls.push(control);
if(this.daysUntil<=14){ //This checks to see if the contacts birthday is within 7 days or less,and creates a warning flag variable so we can display a warning flag
birthdayFlag = "<img src=resources/birthday.png>"
}else{
birthdayFlag = " "
};
if(this.post){ // this checks to see if there is a value in the Postcode attribute, if not it will set the map location to the address entered
mapLocation = this.post;
}else{
mapLocation = this.address;
}
var childDiv =
"<div class='parentDiv'>" +
this.firstName + " " + this.surname + " " + birthdayFlag + "<input type='checkbox' onclick='updateStatus(this.ID)'>" + " " + "<button class='btnForDiv' id='" + buttonid + "'" + " > Click to Expand </button>" +
"<div class='childDiv' id='" + divid + "' " + ">" + "<img class=map src='http://maps.google.com/maps/api/staticmap?scale=1¢er=" + mapLocation + "&zoom=14&size=500x350&maptype=hybrid&markers=size:normal|color:RED|label:C|" + mapLocation + "&sensor=false' style='float: right;border-style:groove'>" +
" " + "<span style='color:#5f9ea0';> Surname: </span>" + "<br>     " + this.surname +
"<BR>  " + "<span style='color:#5f9ea0';> First Name:</span> " +"<br>     " + this.firstName +
"<br>  " + "<span style='color:#5f9ea0';> Date Of Birth:</span> " +"<br>     " + this.days + "/" + this.months + "/" + this.years +
"<br>  " + "<span style='color:#5f9ea0';> Telephone Number:</span> " +"<br>     " + this.phone +
"<br>  " + "<span style='color:#5f9ea0';> Address:</span> " +"<br>     " + this.address + " " + this.post +
"<br>  " + "<span style='color:#5f9ea0';> Email Address:</span> " +"<br>     " + this.email +
"<br>  " + "<span style='color:#5f9ea0';> Group:</span> " +"<br>     " + this.group +
"<br>  " + "<span style='color:#5f9ea0';> Days Until Birthday:</span> " +"<br>     " + this.daysUntil +
"</div>" + "</div>" + "<HR width=1000px>" + "<BR> ";
return childDiv;
}
var updateStatus = function(thisID){
alert("firing");
for (i = 0; i < contacts.length; i += 1) {
if (thisID = contacts[i].ID){
if (contacts[i].toggled = "0"){
contacts[i].toggled = "1";
}else{
if (contacts[i].toggled = "1"){
contacts[i].toggled = "0";
}
}
}
}
}
var assignID = function(){
for (i = 0; i < contacts.length; i += 1) {
contacts[i].ID = "" + i + "" ;
}
}
var removeContacts = function () {
for (i = 0; i < contacts.length; i += 1) {
if (contacts[i].toggled = "1"){
contacts.splice(i,1);
}
}
updateList();
}
var addContact = function(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ){
if(surnameField.value){
a = new Contact(surnameField.value, firstNameField.value,birthdayField.value, phoneField.value, addressField.value, postField.value, emailField.value, groupField.value);
contacts.push(a);
}else{ alert("Please complete all fields")}
}
var clearUI = function(){
var white = "#fff";
surnameField.value = "";
surnameField.style.backgroundColor = white;
firstNameField.value = "";
firstNameField.style.backgroundColor = white;
birthdayField.value="";
birthdayField.style.backgroundColor = white;
phoneField.value = "";
phoneField.style.backgroundcolor = white;
addressField.value = "";
addressField.style.backgroundcolor = white;
postField.value = "";
postField.style.backgroundcolor = white;
emailField.value = "";
emailField.style.backgroundcolor = white;
groupField.value="";
groupField.style.backgroundcolor = white;
}
var updateList = function(elements){
assignID();
myControls = []
var tableDiv = document.getElementById("parentDiv"),
cDiv = "<BR>" ;
for (var i= 0, j=elements.length;i<j;i++){
var cntct = elements[i];
cDiv += cntct.generateDiv();
}
tableDiv.innerHTML = cDiv;
getDate();
daysUntilBirthday();
saveContacts();
}
var add = function(){
;
addContact(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField, imgField);
clearUI();
daysUntilBirthday();
getDate();
updateList(contacts);
updateList(contacts);
};
var saveContacts = function(){
var cntcts = JSON.stringify(contacts);
if (cntcts !==""){
localStorage.contacts = cntcts;
}else{
alert("Could not save contacts");
}
}
var loadContacts = function(){
var cntcts = "";
if(localStorage.contacts !== undefined){
cntcts = localStorage.contacts;
contacts = JSON.parse(cntcts);
var proto = new Contact();
for (var i=0; i<contacts.length; i++){
var cntct = contacts[i]
cntct.__proto__ = proto;
cntct.birthdayDate = new Date(cntct.birthdayDate);
}
}
}
var clearContacts = function(){
contacts = [];
updateList(contacts);
}
var sort_by = function(field, reverse, primer){
var key = function (x) {return primer ? primer(x[field]) : x[field]};
return function (a,b) {
var A = key(a), B = key(b);
return (A < B ? -1 : (A > B ? 1 : 0)) * [1,-1][+!!reverse];
}
}
var sortBySurname = function(){
contacts.sort(sort_by('surname', false, function(a){return a.toUpperCase()}));
updateList(contacts)
}
var sortByFirstname = function(){
contacts.sort(sort_by('firstName', false, function(a){return a.toUpperCase()}));
updateList(contacts)
}
var sortByGroup= function(){
contacts.sort(sort_by('group', false, function(a){return a.toUpperCase()}));
updateList(contacts)
}
var sortByBirthday= function(){
contacts.sort(sort_by('daysUntil', false, parseInt));
updateList(contacts)
}
window.onload = function(){
loadContacts();
updateList(contacts);
surnameField = document.getElementById("surname");
firstNameField = document.getElementById("firstName")
birthdayField = document.getElementById("birthday");
phoneField = document.getElementById("phone");
addressField = document.getElementById("address");
postField = document.getElementById("post");
emailField = document.getElementById("email");
groupField = document.getElementById("group");
imgField = document.getElementById("image");
addButton = document.getElementById("addButton");
addButton.onclick = add;
delButton = document.getElementById("delButton");
searchField = document.getElementById("searchField");
searchButton = document.getElementById("searchButton");
//searchButton.onclick = doSearch();
//delButton.onclick = removeContacts();
sortSurnameButton = document.getElementById("surnameSort");
sortSurnameButton.onclick = sortBySurname;
sortFirstNameButton = document.getElementById("firstNameSort");
sortFirstNameButton.onclick = sortByFirstname;
sortGroupButton = document.getElementById("groupSort");
sortGroupButton.onclick = sortByGroup;
birthSortButton = document.getElementById("birthSort");
birthSortButton.onclick = sortByBirthday;
clearUI();
birthdayCheck();
}
The mistake in overcomplex toggler:
try this:
if (thisID === contacts[i].ID){ //<- HERE WAS MISTAKE - single =
contacts[i].toggled=contacts[i].toggled==="1"? "0": "1"
}
Best to index your contacts by id in Object to avoid loops by id... or just use id when accessing array, you can use this function to generate like UUIDs.
you can acheive that using:
var addContact = function(surnameField,firstNameField,birthdayField, phoneField, addressField, postField, emailField, groupField ){
if(surnameField.value){
a = new Contact(surnameField.value, firstNameField.value,birthdayField.value, phoneField.value, addressField.value, postField.value, emailField.value, groupField.value);
contacts[GUID()]=a;
}else{ alert("Please complete all fields")}
}
the objects will look than like:
{ef9cffdc-9132-af78-6147-6bfc2cb247dc: {object data}, 405e61ae-881e-4b11-eab6-2f2355ca54ae : {object data},}
and will be easy accessed with objects[ID];
single object delete will look like: delete(objects[ID]);
loop will look:
for (var id in objects) {
var object=objects[id];
}
easy enough ?
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;
}