JavaScript - Undefined Object
I've been working through a tutorial on OOP in javascript.
Upon keyup, the code below gives this error: Quote: charCounterObj[x] is undefined This is my first attempt at anything like this, so apologies for what are no doubt egregious and fundamental misunderstnadings about how to implement something like this. I've stripped away everything that's irrelevant, but there's still quite a bit of code here. I'm hoping this isn't too much wade through, but perhaps someone would be kind enough to give it the once-over. There may be something obvious that jumps out to the seasoned eye... Code: //CharCounter Class function charCounterClass(formType) { //Properties this.counter = $('#'+formType+'_commentsCounter'); this.textarea = $('#'+formType+'_comment'); this.maxlength = $('#'+formType+'_commentMaxlength').text(); this.textLen = this.textarea.val().length; //Methods this.cch = function() { $(this.counter).val(this.textLen); //... } } var charCounterObj = []; var charCounter = []; var x = 0; $("input.charCounter").each(function() { charCounter[x] = $(this).val(); if (charCounter[x] == true) { charCounterObj[x] = new charCounterClass(formType[x]); $('#'+formType[x]+'_comment').keyup(function() { charCounterObj[x].cch(); }); } x++; }); Thanks for any input. Similar TutorialsI'm trying to get this assignment done for class. I've spent 3 hours on this part alone. These aren't supposed to be that hard. However, it keeps saying that the variable toppings is undefined. Why is it doing that? Especially since it can find the values when I tell it to print them out with an alert. Yet it won't execute the final part where I go to the confirm. Code: <html> <head> <script> function confirm(theForm) { var selectedItems = ""; var i = 0; for(i =0; i < theForm.toppings.length; i++) { alert(theForm.toppings[i].value); if (theForm.toppings[i].checked==true) { selectedItems = selectedItems + "\n" + theForm.toppings[i].value; } } var r = confirm("You have selected " + selectedItems + "\n" + "Is this correct?"); if (r == true) alert("Ok"); } </script> </head> <body> <form name="form"> <label for="toppings"> <BR><Select name="toppings" MULTIPLE id="toppings"> <OPTION SELECTED> Cheese <OPTION> Pepperoni <OPTION > Onions <OPTION> Sausage <OPTION> Olives </SELECT> <input type="button" value="Confirm selection." onClick="confirm(this.form)"> </form> </body> </html> Never mind, it was because I had named the function "confirm()". A really dumb move on my part. Hello, I'm working on web apps for a company and unfortunately the websites work in Mozilla, chrom and IE9 but not in IE8. In IE8 the error message "undefined is null or not an object" is pointing to this line: temp = val.replace(/-/g, "/"); That line is inside a function. I'm not sure how to troubleshoot this...any help would be appreciated. Edit: digged out some old code , added blue lines, explanation ? Code: comments = new Comments("some text") function Comments(jsp) { this.jsp = jsp; var that = this; this.save = function(obj) { alert(this.jsp);// pops out 'some text' .... ///call ajax ... catch response in catch_save } this.catch_save = function() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { alert(this.jsp);// pops out undefined alert(that.jsp);// pops out 'some text' } } } how come that there is undefined ? I have a bug that is only seeming to effect IE 8:. It seems to have a problem with this line: theSelectBox.selectedIndex = -1; This is where my full page is: http://www.mauirealestate.net/advancedsearch-rets.php Also has a weird display issue in IE8, but not in "compatibility view", which the bug may fix. Works and looks beautiful is Safari and Firefox. Any suggestions are helpful. Hello all. I am trying to track down why this custom validator is failing with an error that args is undefined. There are two funnctions - one works and one does not. Here they a the bold italicized item is where the error is being generated. Function validHygieneNote works as expected however. Code: function validClothingNote(val,args) { var radio_choice = false; var chks = document.getElementById('clothingNote'); var chks2 = document.getElementsByName('clothingInadequate'); for (counter=0; counter < chks2.length; counter++) { if (chks2[counter].checked){ var rad_val =chks2[counter].value; }} if((rad_val==1)|| (rad_val==2)) { if ((chks.value=="") || (chks.value.length==0) || (chks.value==null)){ args.IsValid=false; } else { args.IsValid = true; } }} function validHygieneNote(val,args) { var radio_choice = false; var chks = document.getElementById('hygieneNote'); var chks2 = document.getElementsByName('hygieneInadequate'); for (counter=0; counter < chks2.length; counter++) { if (chks2[counter].checked){ var rad_val =chks2[counter].value; }} if((rad_val==1)|| (rad_val==2)) { if ((chks.value=="") || (chks.value.length==0) || (chks.value==null)){ args.IsValid=false; } else { args.IsValid = true; } }} I created a new Javascript *class* Code: function TableData(headers, row) { this.headerArr = headers; this.rowArr = row; } TableData.printTable = function() { alert("hello"); for(i=0; i<this.headerArr.length; i++) { document.write('<tr><th>'); document.write(this.headerArr[i]); document.write('</th><td>'); document.write(this.rowArr[i]); document.write('</td></tr>'); } } when I call it, though (printTable()) i get the error Value undefined (result of expression parent.B.obj.printTable) is not object. i dont rly understand javascript functions... but i think that should work? idk i call it on an onclick event Hey, I have made/modifying a script that I can create AJAX objects on the fly. It is working fine in Chrome, FF, Opera, Safari but not IE -.- IE = nightmare Code: function ajax_object() { this.receive = function(serverAJAXpage, whileLoading, onDone, dataIntoDivID) { this.xmlHttp = createAjaxObject(); this.serverAJAXpage = serverAJAXpage; this.xmlHttp.open("GET", this.serverAJAXpage, true); this.xmlHttp.send(); this.xmlHttp.onreadystatechange = function() { if (this.readyState == 1) { eval(whileLoading); //document.getElementById(mydiv).innerHTML=this.responseText; } if (this.readyState == 4) { eval(onDone); if (typeof dataIntoDivID != "undefined") { document.getElementById(dataIntoDivID).innerHTML = this.responseText; } } } } } function createAjaxObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } There is the function that handles the object and here is the objects being used: Code: <script> var onlineUsersAJAX = new ajax_object(); onlineUsersAJAX.receive('ajax/onlineUsers.php', '', '', 'onlineUsers'); var recentPostsAJAX = new ajax_object(); recentPostsAJAX.receive('ajax/recentPosts.php', '', '', 'recentThreads'); </script> IE throws the error: 'ajax_object' is undefined Thank you to anyone that can help =) Hi, I started getting a wierd problem with my jscript program. Here im using jscript for client-side validation and upon email field submission,im getting undefined value with an error saying "length is null or not an object". All the values of fields prior to that are being obtained properly. Please help me out of this crisis I do not really understand what is happening to my code but it just tell me the following: Code: document.getElementById("#movingword") is null How could the movingword be null when I have declared it in my code? The following is my code: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="language" content="english"> <meta http-equiv="Content-Style-Type" content="text/css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <title></title> <style type="text/css"> body { background-color:#000; } #scenery { position:relative; } #moving { position:absolute; float:right; top:100px; left:50px; } #movingword { position:absolute; float:right; top:0px; left:0px; } </style> <script type="text/javascript"> var a=120; $(document).ready(function() { document.getElementById("#movingword").style.top = a + "px"; }); </script> </head> <body> <font color=white><h1> Hello World </h1></font> <div id="scenery"> <img src="http://www.deshow.net/d/file/travel/2009-10/new-zealand-scenery-738-20.jpg" alt=""> <div id="moving"> <img src="http://maadinfo.com/images/blinking.gif" alt=""> </div> <div id="movingword"> <font color="yellow"><font size="3"><b>This is the place</b></font><br>Welcome!</font> </div> </div> </body> </html> Hiya, I would like to ask your help regarding this damned error message that comes out only in Internet Explorer and makes impossible to submit the form. The javascript code is: Code: function checkForm() { var cname, cspouse, cemail, chphone, ccellular, caddress, ccity, cstate, czip, cpets, cvolunteer, cadditional; with(window.document.volApplForm) { cname = Name; cspouse = Spouse; cemail = Email; chphone = HomePhone; ccellular = Cellular; caddress = Address; ccity = City; cstate = State; czip = Zip; cpets = Pets; cvolunteer = Volunteer; cadditional = Additional; } var ALERT_TITLE = "Oops!"; var ALERT_BUTTON_TEXT = "Close"; if(document.getElementById) { window.alert = function(txt) { createCustomAlert(txt); } } function createCustomAlert(txt) { d = document; if(d.getElementById("modalContainer")) return; mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div")); mObj.id = "modalContainer"; mObj.style.height = document.documentElement.scrollHeight + "px"; alertObj = mObj.appendChild(d.createElement("div")); alertObj.id = "alertBox"; if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px"; alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px"; h1 = alertObj.appendChild(d.createElement("h1")); h1.appendChild(d.createTextNode(ALERT_TITLE)); msg = alertObj.appendChild(d.createElement("p")); msg.innerHTML = txt; btn = alertObj.appendChild(d.createElement("a")); btn.id = "closeBtn"; btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT)); btn.href = "#"; btn.onclick = function() { removeCustomAlert();return false; } } if(trim(cname.value) == '') { alert('Please enter your name'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cname.focus();} return false; } else if(trim(cemail.value) == '') { alert('Please enter your email'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cemail.focus();} return false; } else if(!isEmail(trim(cemail.value))) { alert('Email address is not valid'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cemail.focus();} return false; } else if(trim(chphone.value) == '') { alert('Please enter your valid phone number'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); chphone.focus();} return false; } else if(trim(ccellular.value) == '') { alert('Please enter valid cell phone number'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); ccellular.focus();} return false; } else if(trim(caddress.value) == '') { alert('Please enter your valid address'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); caddress.focus();} return false; } else if(trim(ccity.value) == '') { alert('Please enter your city'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); ccity.focus();} return false; } else if(trim(cstate.value) == '') { alert('Please enter valid state name'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cstate.focus();} return false; } else if(trim(czip.value) == '') { alert('Please enter valid zip code'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); czip.focus();} return false; } else if(trim(cvolunteer.value) == '') { alert('Please fill in all fields'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cvolunteer.focus();} return false; } else if(trim(cadditional.value) == '') { alert('Please fill in all fields'); function removeCustomAlert() {document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer")); cadditional.focus();} return false; } else { cname.value = trim(cname.value); cspouse.value = trim(cspouse.value); cemail.value = trim(cemail.value); chphone.value = trim(chphone.value); ccellular.value = trim(ccellular.value); caddress.value = trim(caddress.value); ccity.value = trim(ccity.value); cstate.value = trim(cstate.value); czip.value = trim(czip.value); cpets.value = trim(cpets.value); cvolunteer.value = trim(cvolunteer.value); cadditional.value = trim(cadditional.value); return true; } } function trim(str) { return str.replace(/^\s+|\s+$/g,''); } function isEmail(str) { var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn |bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk| dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs |gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr| kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum |mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr |pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf |tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za| zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i; return regex.test(str); } And when trying to submit the form, I get the error message: Code: Line: 177 Character: 4 Code: 0 Error Message: 'undefined' is null or not an object URL: https://localhost/ruff/scripts/validationVol.js Do you have an idea what could be the problem? As I checked line 177, it seems to be OK. I checked the web, but didn't find anything related to this message in a situation like this. Thanks in advance for your comments. Hi, every time I try and alert: [ { number:0, secondnumber:0 }, { number:2, secondnumber:1 }, { number:1, secondnumber:2 } ] it just shows [object object], [object object], [object object]. Why is this and what can I do to make the record be shown as it is above in an alert? Thanks. I can't get any info from Firebug except that one line, uncaught exception [object Object]. The code fully worked, then I needed to make it dynamically create Sortables from the scriptaculous library based on how many X were in a table in my database, which I've done, and I'm thinking it may be a simple slight parse error of some type, I'm not too good with Javascript, because now my script barely works. I've double checked the script's source code, the PHP variables are exactly what they should be. Code: print<<<HERE Sortable.create('sortlist$box', { tag: 'img', overlap:'horizontal',constraint:false, containment: $list, dropOnEmpty: true, onChange: function(item) { var list = Sortable.options(item).element; if(changeEffect) changeEffect.cancel(); changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" }); }, onDrop: function(item) { var thing=Sortable.options(item).element.identify(); var anchors = document.getElementById(thing).childNodes.length-2; if(anchors > 20){ alert('This box had 20 creatures in it already, your last action has not been saved.'); window.location.reload(); } else{ new Ajax.Request("saveImageOrder.php", { method: "post", parameters: { data: Sortable.serialize("sortlist$box") } }); } } }); HERE; $box++; } ?> }); </script> if you solve this I'll send ya $10 via paypal I created a method for displaying an object's properties: Code: renderfunction = false; function showProperty (object, property) { document.write ('<td class="type">' + (typeof object[property]) + '</td>' + '<td class="name">' + property + '</td>'); document.writeln('<td class="value">' + ( (typeof object[property] != 'function') ? object[property] :( (property != 'showProperties') ? ( renderfunction ? object[property]() : ('<span class="self">NOT RENDERED</span>') ) : ('<span class="self">THIS</span>') ) ) + '</td>'); document.writeln('<td class="hasOwnProperty" >' + ( object.hasOwnProperty(property) ? "Local" : "Inherited" ) + '</td>'); if (typeof object[property] == 'function') { document.writeln ('<td class="function">' + object[property] + '</td>'); } else { document.writeln ('<td class="function"> </td>'); } } As long as renderfunction = false, the object is fine coming out of this function. However, if I change renderfunction to true, all my properties become undefined. Why isn't this working as I expect it to? How should I fix it? Thanks in advance, -Brian. Ignore post (if mod, please delete)
Hello together! I generate html code with jsp. In that jsp there a several framesets and frames. And yes i know, frames are not really up to date but it's an old program and i have to deal with it now. Anyway, in the top frameset i have an onload attribute like onload="load()". In the function load i want to access the Element.prototype object. But unfortunately typeof Element gives me "undefined". So i looked a little deeper and found that window.toString() gives me "[object]" and not as expected "[object window]" so somehow my window doesn't know that its construcor is Window. window.construcor is "undefined" as well. And i don't have access to the Element object. I really don't know where the error could be. When the page is loaded and i access the same window over the console, then everything is right. But in my function a can't get access to the objects i need. I also don't know what part of the code could be useful to post here, but maybe someone had a similar problem before? i should say that this problem only occurs in IE8. In IE9 it works perfectly. Has anyone any idea?? Hi all, I'm stumped on finding a way in javascript to create an object factory whose instances are also object factories. In short I want something like that below, but no joy ... any clues? Code: function createClass () { return new createClass() function createClass() { return new createInstance () function createInstance () { //Default properties, values and methods which might later be extended } } } var createDoor = createClass(); var door1 = createDoor(); var door2 = createDoor(); var createChair = createClass(); var chair1 = createChair (); var chair2 = createChair (); I'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. Hello. Is there any way to get the variable name of an object from inside the object? E.g. PHP Code: function Bla(){ this.write = function(){ document.write(<objectname>); } } obj1 = new Bla(); obj1.write(); //Outputs obj1 Here is my script: PHP Code: function myTimer(seconds, obj){ this.seconds = seconds; this.obj = obj; this.startTimer = function(){ if(this.seconds>0){ this.seconds--; this.obj.innerHTML = this.seconds; this.timer = setTimeout("Timer.start()",1000); } } } Timer = new Timer(10, obj); Timer.startTimer(); Now the problem is that the variable that contains the object must be named "Timer". This way I cannot create new timer objects with different variable names I have tried: this.timer = setTimeout("this.start()",1000); but it doesn't work. That's why it would be good to detect the variable name and instead use something like this: this.timer = setTimeout(varname+".start()",1000); I would rather not have to pass the variable name through a parameter like this: Timer1 = new Timer(10, obj, "Timer1"); Thanks in advance. Quote: menu: function( a, b ) { $( b ).observe( 'click', function( event ) { event.stop(); if( $( a ).visible() ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } else { $( a ).show(); $( b ).addClassName( 'selected' ); document.observe( 'click', function( e ) { if( e.target.id != a && e.target.id != b && !Element.descendantOf( e.target, $( a ) ) ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } }); } }); $$( '#' + b + ' > a' ).each( function( element ) { element.observe( 'click', function( event ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); }); }); } This work's perfrect accept when i use it with others on the menu it leaves the other ones open, how do i get it to close the open one when i open a new menu.. Thanks. |