JavaScript - An Object Is Undefined Yet It Knows What It Is In Alerts
I'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. Similar TutorialsI'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. 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 ? 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. 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 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. 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> Ok, I need some help with this. When you click the close button on your browser, I want it to have a confirmation. Saying "**Click OK to be redirected to a new page**" something like that. If you click "OK" you are redirected to another page. If you hit CANCEL, then it closes out. It doesn't have to be a confirmation. Just needs to be something that has an option. (Maybe return xx?) Anyways, here's what I've got: Code: <script type="text/javascript" language="javascript"> var sure = false; var lin = false; function sureF() { if(!sure && !lin) { sure = true; var con = confirm("**Are you sure you want to leave?**") if(con == true) { location.href = "http://www.google.com/" return con; } else { alert("Sorry") } } } window.onbeforeunload = sureF; </script> What that does, is when you click close on your browser, it will say "Are you sure you want to leave?" you click "OK", and you get redirected to google .com (How I set it) BUT then a popup comes up saying, "Are you sure you want to navigate away?" which I don't want at all. As you can see, my script is quite messed up. Could you help me out? Thanks. http://becompleteamerica.com/index.p...tact&Itemid=80 It works awesome in all browsers but IE 7 & 8. The custom "alert" is actually a dialog box, with a background fader underneath it, kind of like lightbox. Any ideas why IE doesn't play nice? Thx 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. I'm just starting out with javascripting and am trying to make a Choose your own Adventure game. My goal is to have the scenes and alerts change depending on the button clicked, but I'm stuck, unfortunately. I keep getting the same alerts repeated and my image doesn't change. I think I'm missing code or have made a mistake somewhere, but have no idea what I've done wrong or left out. I don't know if this type of programming has a more specific name, too, so I wasn't sure what to search for to get help. Hopefully someone can guide me in the right direction. I've included my beginning code below. Thanks Code: <script type="text/javascript"> var curScene = "0"; function userChoice(decision){ alert(decision); /*welcomepage*/ if(curScene == 0) { alert("Welcome to the game. Chose 1 or 2."); }if(decision == 1) { alert(); curScene = 1; }else if(decision == 2){ alert(); curScene = 1; } /*Scene1*/ if(curScene == 1){ alert("go left or right"); }if(decision == 1) { alert("you went left and fell in a hole"); curScene = 3; }else if(decision == 2){ alert("you go right and come upon a zebra"); curScene = 4; } } document.getElementById("sceneimg").src= "scene" + curScene + ".jpg"; </script> <img id="sceneimg" src="scene0.jpg" alt= "Stick Figure Adventure" /> <input type="button" value="1" onClick= "userChoice(1)"> <input type="button" value="2" onClick= "userChoice(2)"> </script> 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)
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 (); |