0

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&center=" + mapLocation + "&zoom=14&size=500x350&maptype=hybrid&markers=size:normal|color:RED|label:C|" + mapLocation + "&sensor=false' style='float: right;border-style:groove'>" +
                "&nbsp" + "<span style='color:#5f9ea0';> Surname: </span>"  + "<br> &nbsp&nbsp&nbsp&nbsp" + this.surname +
                "<BR> &nbsp" + "<span style='color:#5f9ea0';> First Name:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.firstName +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Date Of Birth:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.days + "/" +  this.months + "/" + this.years +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Telephone Number:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.phone +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Address:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.address + " " + this.post +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Email Address:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.email +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Group:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.group +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Days Until Birthday:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + 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&center=" + mapLocation + "&zoom=14&size=500x350&maptype=hybrid&markers=size:normal|color:RED|label:C|" + mapLocation + "&sensor=false' style='float: right;border-style:groove'>" +
                "&nbsp" + "<span style='color:#5f9ea0';> Surname: </span>"  + "<br> &nbsp&nbsp&nbsp&nbsp" + this.surname +
                "<BR> &nbsp" + "<span style='color:#5f9ea0';> First Name:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.firstName +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Date Of Birth:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.days + "/" +  this.months + "/" + this.years +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Telephone Number:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.phone +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Address:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.address + " " + this.post +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Email Address:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.email +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Group:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + this.group +
                "<br> &nbsp" + "<span style='color:#5f9ea0';> Days Until Birthday:</span> " +"<br> &nbsp&nbsp&nbsp&nbsp" + 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();

}
Shuma
  • 283
  • 3
  • 5
  • 16
  • It seems to me like you've written a shitload of code that does'nt really do much ? – adeneo Dec 09 '12 at 00:34
  • Perhaps, I'm fairly new to this. Everything works as intended(excluding the subject of this post), there's no redundant code that I'm aware of, probably a lot of inefficient code though. – Shuma Dec 09 '12 at 00:37
  • @Shuma can you create jsfiddle wich will demostrate problem ? here is too much code to read out, `checkbox` have no `toggled` attribute, it has `checked` attribute – zb' Dec 09 '12 at 00:48
  • http://jsfiddle.net/oceog/f6NFe/ see how it works, no problem that div was generated, you just need to store somewhere pointer to the checkbox you want a check – zb' Dec 09 '12 at 01:16
  • ok readed code out, so `toggled` is just a property of the `Contact` – zb' Dec 09 '12 at 01:24
  • Yes, sorry I'm being a bit confusing. Tried to make a fiddle but it wouldn't work for some reason – Shuma Dec 09 '12 at 01:28

1 Answers1

0

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 ?

Community
  • 1
  • 1
zb'
  • 8,071
  • 4
  • 41
  • 68
  • This is perfect! Exactly what i was looking for, I'll implement and let you know if it works, thankyou! – Shuma Dec 09 '12 at 01:57