JavaScript - Error: Object Is Not A Constructor Javascript?
I am trying to understand why I had an error, or why my solution worked.
In my HTML I had: Code: <script language="JavaScript" type="text/javascript" src="Book.js"></script> <script language="JavaScript" type="text/javascript" src="Book_TEST.js"></script> Book.js said: Code: function Book(title, author) { this.title = title; this.author = author; } Book.prototype.toString = function() { return '"' + this.title + '" by '+ this.author; }; var Book = new Book ("John", "Dough"); alert (Book); // displays "John Dough" And, predictably, at this stage, the code worked. Book.js said: Code: var myBook = new Book ("JavaScript Tutorials", "Herong Yang"); However, at this point the JavaScript would crash and I'd get an error "Error: Book is not a constructor javascript." I drove myself nuts trying to figure out why the code wasn't working at this later point. Eventually, I copied another object: Code: /* * Person class */ /** * Person constructor * * @param {String} first * The person's first name * @param {String} last * The person's last name */ function Person(first, last) { this.first = first; this.last = last; } /** * Create a string representation of this object * * @return {String} A string representation of this object */ Person.prototype.toString = function() { return this.first + " " + this.last; }; /* var person = new Person ("John", "Dough"); alert (person); // displays "John Dough" */ and then used find and replace to swap {Person, first, last} with {Book, title, author}, resulting in: Code: /* * Book class */ /** * Book constructor * * @param {String} title * The Book's title * @param {String} author * The Book's author */ function Book(title, author) { this.title = title; this.author = author; } /** * Create a string representation of this object * * @return {String} A string representation of this object */ Book.prototype.toString = function() { return '"' + this.title + '" by '+ this.author; }; var Book = new Book ("John", "Dough"); alert (Book); // displays "John Dough" Now, the code worked fine in both script. (i.e., no more error.) So far as I can tell, the only differences between the first and next version of Book.js are the comments and the whitespace. Am I missing something? Can the comments or whitespace somehow effect the logic with which this code has been executing? If I get an error like this again, is there an easier/better way to fix it than to essentially retype the code? Thanks in advance for helping me to understand this. Similar TutorialsI need to detect the "name" of the constructor of an object. For example, myArray.constructor === Array is true, but I want something where that === 'Array' is true. I've heard of Object.constructor.name, but it's not widely compatible. Any ideas (preferably without involving regular expressions)? Thanks in advnce, Julian hi, I am trying to setup an iphone application in Dashcode using what I have he http://www.mypubspace.com/dashtest/order.html Result of expression 'ajaxDisplay' [null] is not an object which is on the following line: Code: ajaxDisplay.innerHTML = ajaxRequest.responseText; is there a way around this? thanks Hi I am using a custom form elements script in the link below: www_bristolstreet_co_uk/page/find_a_dealer.htm and an error for null object is appearing from this line: active = option[0].childNodes[0].nodeValue; Can anyone please help? I am a novice at Javascript but got this script working perfectly on my local machine - once I loaded it the live site it didn't work... any advice would be greatly appreciated. Hello I am using a timer which goes down from 2 minutes to zero when 'jsp' is called. Timer is written in javascript. I am getting an error that document.form1.timerMin.value=<%=min%> is null or not an object. Here is the code (t.jsp): <% /* Default timer */ int min = 2; int sec = 5; /* Check for timer params */ try { String timerMin = request.getParameter("timerMin"); if (timerMin==null)timerMin=""; if (timerMin != null) { min = Integer.parseInt(timerMin); } String timerSec = request.getParameter("timerSec"); if (timerSec==null)timerSec=""; if (timerSec != null) { sec = Integer.parseInt(timerSec); } } catch(Exception m) { System.out.println("generated exception..............:"+m); } %> <script language="JavaScript" type="text/javascript"> <!-- /* Initialise timer */ var min = <%=min%>; // set the minutes var sec = <%=sec%>; // set the seconds function countDown() { sec--; if (sec == -1) { sec = 59; min--; } /* Write timer state to hidden form fields */ document.form1.timerMin.value=<%=min%> document.form1.timerSec.value=<%=sec%>; time = (min<=9 ? "0" + min : min) + " min and " + (sec<=9 ? "0" + sec : sec) + " sec "; document.getElementById('theTime').innerHTML = time; SD=window.setTimeout("countDown()", 1000); if (min == 0 && sec == 0) { window.clearTimeout(SD); } } window.onload = countDown(); --> </script> <style type="text/css"> <!-- .timeClass { font-family:arial,verdana,helvetica,sans-serif; font-weight:normal; font-size:10pt; } --> </style> <table width="100%"> <tr><td width="100%" align="right"> <span id="theTime" class="timeClass"></span> </td></tr> <form method="post" name="form1" id="form1" action="t.jsp" <td width="50%" valign="middle"> <input type="hidden" name="timerMin" value="<%=min%>"> <input type="hidden" name="timerSec" value="<%=sec%>"> <div align="center"><a href="javascript:form1.submit()" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('Image3','','/lms/images/submit_0.gif',1)"><img name="Image3" border="0" src="/lms/images/submit_0.gif" width="70" height="30"></a></div> </td> </form> Looking forward for an early reply. Thanks Hi All, I am using javascript to get the number of rows in my HTML Table by using below code: Code: var oRows = document.getElementById("HTMLTable").getElementsByTagName('tr'); var iRowCount = oRows.length; Later I am using iRowcount in the FOR loop further in my code as below: Code: for(k=1; k<=iRowCount; k++) { ............................ rest of code ........... ............................ } This piece of code is working fine (i.e. it handles the functionalities which is needed) but it also opens a new browser window with the error message "Object Required".I have really no idead why this is happening.Can anyone suggest me the reason for this? Thanks in advance. -Anil Hey Guys, I wondered if anyone would be kind enough to look at an issue I am having running a Javascript on IE. The script works fine in FF and Chrome but chucks up an error in all versions of IE so the Menubar does not display child pages. Here's the Error: User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) Timestamp: Tue, 16 Aug 2011 14:45:53 UTC Message: 'lastChild' is null or not an object Line: 31 Char: 3 Code: 0 The full script is he http://www.makingtrails.com/wp-conte...ks3/js/menu.js Any help much appreciated as the author of this script is not providing any support. Thanks Jon I had read from books that the constructor property of object is inherited from its prototype. And the prototype can be changed dynamically. New property can be added to or deleted from object even it was created before the prototype change. But I got confused on below codes. Code: function A() { this.title = "A"; } function B() { this.title = "B"; } document.write("<br>"); var b = new B(); document.write(b.constructor); document.write("<br>"); document.write(B.prototype.constructor); document.write("<br>"); B.prototype = new A(); document.write(b.constructor); // Suppose to output "function A() ..." document.write("<br>"); document.write(B.prototype.constructor); document.write("<br>"); B.prototype.constructor = B; document.write(b.constructor); document.write("<br>"); document.write(B.prototype.constructor); document.write("<br>"); But the actual result (both IE and firefox) is Code: function B() { this.title = "B"; } function B() { this.title = "B"; } function B() { this.title = "B"; } function A() { this.title = "A"; } function B() { this.title = "B"; } function B() { this.title = "B"; } Please help me. thanks. When I run this program is says I have an object error (not found?) in line 2, I went over the program which I copied from a book over and over and not finding anything wrong... Help!!! thanks HTML code he Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Making Sums</title> <script type="text/javascript" src="jsb-08-01.js"></script> <script type="text/javascript" src="jsb-global.js"></script> </head> <body> <h1>Making Sums</h1> <form action="addit.php"> <p><input type="text" id="inputA" name="inputA" value="0" /></p> <p><input type="text" id="inputB" name="inputB" value="0" /></p> <p><input type="button" id="add" name="add" value="Add" /></p> <p><input type="text" id="output" name="output" /></p> </form> </body> </html> Javascript code he Code: // initialize when the page has loaded addEvent(window, 'load', initialize); // Here's where it says I have an error function initialize() { // do this only if the browser can handle DOM methods if(document.getElementById) { // point to critical elements var oInputA = document.getElementById('inputA'); var oInputB = document.getElementById('inputB'); var oButton = document.getElementById('add'); var oOutput = document.getElementById('output'); // if they all exist... if(oInputA && oInputB && oButton && oOutput) { //apply behaviors addEvent(oButton, 'click', addIt); } } } // add two input numbers & display results function addIt() { var value1 = document.getElementById("inputA").value; var value2 = document.getElementById("inputB").value; document.getElementById("output").value = value1 + value2; } Hi guys i am trying to make my form out put inputs to the table below. however when i debug in ie9 it tells me error object expected for Code: <button onclick="document.getElementById('tablename').value= document.getElementById('name').value">Submit</button> how do i properly declare the object? the full code is below (i will obviously have more input fields just working it all out first) thanks david Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8" /> <title> HiQuote </title> <!-- Local JavaScripts --> <script type="text/javascript"> // -------------------------------------------- // the 'program' - the CONTROL LAYER function getElementById(" " ) { button onclick="document.getElementById(" ") } // --------------------------------------------- // The global variables - the PERSISTENCE LAYER (sort of!) var Name; var Number; var button onclick="document.getElementById(" ") // --------------------------------------------- // The processing functions - the LOGIC LAYER // --------------------------------------------- // The input/ output functions - the PRESENTATION LAYER // THIS enhanced presentation layer uses a web page form for input // and output. </script> </head> <body> <form name="form" action=" " > INPUT DATA:<br/><br/> Customer name (text): <input name="dataInputName" type = "text" size="30" /><br/><br/> Phone number (text): <input name="dataInputNumber" type ="text" size="10" /><br /><br /> <button onclick="document.getElementById('tablename').value= document.getElementById('name').value">Submit</button> </form> <table> <tr> <td id="tablename"> </td> </tr> <tr> <td id="tablenumber"> </td> </tr> </table> </body> </html> Hi, I am getting an error on this code - sometimes! - and I'm not sure what it is. If I run this as is there is no error. If I add it into another page with other stuff it's ok for a while and then I get an error. So, I added my new page block my block to this code and waited for the error to appear so I could determine a conflict - but it was fine. And then a few clicks later the error. This is the error in IE. In Firefox it seems to be fine lol. Line 159 Char 3 'window.document.sendform.message_text' is null or not an object Can someone make any suggestions? Code: <script language="JavaScript" type="text/javascript"> maxlen = 160; countLen(); function countLen() { message_text = window.document.sendform.message_text.value; realLength = message_text.length; if (realLength>maxlen) { realLength = maxlen; window.document.sendform.message_text.value = message_text.substring(0,maxlen); } message_text = window.document.sendform.message_text.value; // del enter var m = message_text.match(/[\r\n]/); if (m !== null) { window.document.sendform.message_text.value = message_text.replace(/[\n\r]/g, '') } window.document.sendform.messlen.value=maxlen-realLength; } </script> <cfset thismessage = "Hi, is this a start"> <cfform action="step2.cfm" method="post" id="sendform" name="sendform"> <cfoutput><textarea id="styled" name="message_text" onkeypress=countLen() onkeydown=countLen() onkeyup=countLen() onchange=countLen() onmouseover=countLen() rows="4">#thismessage#</textarea></cfoutput> <table width="331" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="5"></td> <td width="26"><cfoutput> <input name="messlen" type="text" value="160" class="counterField" onFocus="this.form.message_text.focus();" /></cfoutput></td> <td width="300">characters remaining</td> </tr> </table> </cfform> Thanks! Much appreciated! Kind regards, jo Hi All, I always get "Object Required" error when using IE (all IEs). No error when using FF. Message: Object required Line: 62 Char: 178 Code: 0 URI: I am using WebFXTabPane JS and always get error on line 62 or 63. Below is the excerption for line 62 and 63: }; WebFXTabPane.prototype.getSelectedIndex = function () { return this.selectedIndex;}; WebFXTabPane.prototype.addTabPage = function ( oElement ) { if ( !hasSupport() ) return; if ( oElement.tabPage == this ) return oElement.tabPage; var n = this.pages.length; var tp = this.pages[n] = new WebFXTabPage( oElement, this, n ); tp.tabPane = this; this.tabRow.appendChild( tp.tab ); if ( n == this.selectedIndex ) Thank you in advance for any help. Cheers, Jo Hi, I have an "Object Required" error that only appears in IE and refers to a js file that I got elsewhere, so I'm kind of lost as to how to debug it. The page (which works fine in Chrome and FF) is here and the error reported is: Line: 7 Error: Object Required Sometimes it doesn't pop an alert, but mostly it does. thanks in advance for any suggestions. The website is CnJ-Tree.atwebpages.com The site works in everything, except, IE. Of course, never fails right. Anyway, the error is with the navigation. I keep getting object expected errors, on pretty much all of my onMouseOver, onMouseOut, and onClick events. Here is the html. Code: <tr> <td background="images/CnJ-Layout_04.png" width="720" height="28" valign="middle" align="center"> <div id="container" class="navigation"> <a href="#" onClick="openPage('home.php');"><div id="home" class="home" align="center" onMouseOver="navOpen('home');" onMouseOut="navClose('home');">Home</div></a> <a href="#" onClick="openPage('contact.php')"><div id="contact" class="contact" align="center" onMouseOver="navOpen('contact')" onMouseOut="navClose('contact')">Contact Us</div></a> <div id="service" class="service" align="center" onMouseOver="mopen('serviceDropDown'); navOpen('service');" onMouseOut="mclosetime(); navClose('service');" style="cursor:pointer">Services</div> <div id="serviceDropDown" class="serviceDropDown" align="center" onMouseOver="mcancelclosetime(); navOpen('service');" onMouseOut="mclosetime(); navClose('service');" style="visibility: hidden"> <div id="tree" style="cursor:pointer" onClick="openPage('tree-removal.php')" onMouseOver="navOpen('tree')" onMouseOut="navClose('tree')">Tree Removal</div> <div id="trimming" style="cursor:pointer" onClick="openPage('tree-removal.php')" onMouseOver="navOpen('trimming')" onMouseOut="navClose('trimming')">Tree Trimming</div> <div id="hauling" style="cursor:pointer" onClick="openPage('tree-removal.php')" onMouseOver="navOpen('hauling')" onMouseOut="navClose('hauling')">Any Hauling</div> </div> <div id="about" class="about" align="center" onMouseOver="navOpen('about')" onMouseOut="navClose('about')">About Us</div> <div id="gallery" class="gallery" align="center" onMouseOver="navOpen('gallery')" onMouseOut="navClose('gallery')">Gallery</div> </div> </td> </tr> And here is the JS for the related areas. Code: <script type="text/javascript"> var xmlhttp window.onload=function(){ var dotspan = document.getElementById('dots'); window.setInterval(function(){ if(dotspan.innerHTML == '...'){ dotspan.innerHTML = '.'; } else{ dotspan.innerHTML += '.'; } }, 200); // Initiate AJAX usage try { xmlhttp = new XMLHttpRequest(); } // Firefox, Opera 8.0+, Safari catch(e){ try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } // Internet Explorer catch(e){ try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } // Internet Explorer catch(e){ alert("Your browser does not support AJAX!"); return false; } } } } function navOpen(page) { document.getElementById(page).style.backgroundImage = "url(images/navi-rollover.png)"; document.getElementById(page).style.color = "#787864"; } function navClose(page) { document.getElementById(page).style.backgroundImage = ""; document.getElementById(page).style.color = "#9b9b80"; } var timeout = 500; var closetimer = 0; var ddmenuitem = 0; // open hidden layer function mopen(id) { // cancel close timer mcancelclosetime(); // close old layer if(ddmenuitem) ddmenuitem.style.visibility = 'hidden'; // get new layer and show it ddmenuitem = document.getElementById(id); ddmenuitem.style.visibility = 'visible'; } // close showed layer function mclose() { if(ddmenuitem) ddmenuitem.style.visibility = 'hidden'; } // go close timer function mclosetime() { closetimer = window.setTimeout(mclose, timeout); } // cancel close timer function mcancelclosetime() { if(closetimer) { window.clearTimeout(closetimer); closetimer = null; } } // close layer when click-out document.onClick = mclose; window.onload=function(){ // Initiate AJAX usage try { xmlhttp = new XMLHttpRequest(); } // Firefox, Opera 8.0+, Safari catch(e){ try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } // Internet Explorer catch(e){ try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } // Internet Explorer catch(e){ alert("Your browser does not support AJAX!"); return false; } } } } function openPage(id) { xmlhttp=GetXmlHttpObject(); if (xmlhttp==null) { alert ("Your browser does not support XMLHTTP!"); return; } var url=id; xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState !=4){ document.getElementById("main").innerHTML=("<center><img src='http://upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif'></center>"); } else{ document.getElementById("main").innerHTML=xmlhttp.responseText; } } ; xmlhttp.open("GET",url,true); xmlhttp.send(null); function GetXmlHttpObject() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari return new XMLHttpRequest(); } if (window.ActiveXObject) { // code for IE6, IE5 return new ActiveXObject("Microsoft.XMLHTTP"); } return null; } } </script> Hi - New to Javascript - new to the forum... Here's one that I don't understand: Code: <script type="text/javascript"> fso = new ActiveXObject("Scripting.FileSystemObject"); myCollection = new Collection(); function FindFiles() { var path = "c:\\files\\"; var ext = ".csv"; var files = new Enumerator (fso.GetFolder(path).Files); //Collect all files in path do { var file = files.item(); if (file.Name.indexOf("_summary")<0) myCollection.add(file.Name,file.Type); files.moveNext(); } while (!files.atEnd()); } function Collection() { var collection = {}; var order = []; this.add = function(property, value) { if(!this.exists(property)) { collection[property]=value; order.push(property); } } this.exists = function(property) { return collection[property]!=null; } } function ListCollection() { var g = new Enumerator (myCollection); do { var colitem = g.item(); g.moveNext(); } while (!g.atEnd()); } </script> During execution, I get a "Object not a collection" error when I try to pass "MyCollection" to the Enumerator function. What am I missing? Thanks, Max Hi, I'm trying to get the below code working... But it seems to be throwing an error when the function hitcount(fn) is called... Im trying to call an ASP function within Javascript... Can any one please help with this : Code: -- Javascript code -- <script LANGUAGE="JavaScript1.2" > function checkurl(fn) { str = "http://webhost.in/PNM/Book/<%=gotorpt%>/" + fn; if (str.indexOf ("web//") > 0) { alert("Please Select a Month!"); } else { str2 = "http://webhost.in/PNM/Book/counter.asp?choserpt=Y&whichyrmth=" + str; hitcount(fn); -- Error occurs here : Object Expected self.location.href = str; } return; } </script> --ASP function -- <% function hitcount(fn) set conn=Server.CreateObject("ADODB.Connection") conn.Provider="Microsoft.Jet.OLEDB.4.0" conn.Open "..\Hits\hitcounter.mdb" -- Database conn.Mode = 3 set rs = Server.CreateObject("ADODB.Recordset") set SQL = "UPDATE Application_counter SET Application_counter.[Counter] = Application_counter.Counter+1 where pdf='"+fn.substring(0,8)+"';" rs.Open SQL,conn,1,3 document.write(rs(0)) rs.Close() cn.Close() end function %> i keep getting this error in explorer, while on chrome and on Firefox, it is just not working. this is the html table, (the relevant part is bold) Code: <table align="center"> <tr> <td> שם: </td> <td> <input type="text" id="uname" name="txtname" value="שדה חובה" onmouseout="chkfld('uname')" onclick="this.value='';" /> </td>] </tr> <tr> <td> טלפון: </td> <td> <input id="phone" type="text" name="txtphone" /> </td> </tr> <tr> <td> אימייל: </td> <td> <input type="text" id="usermail" name="txtemail" value="שדה חובה" onmouseout="chkfld('usermail')" onclick="this.value='';" /> </td> </tr> <tr> <td> סיבת הפניה: </td> <td> <select id="reason"> <option>סדנאות</option> <option>טיפול</option> <option>הורדת משקל</option> <option>ניקוי רעלים</option> <option>כללי</option> </select> </td> </tr> <tr> <td> פרטים: </td> <td> <textarea id="TextArea1" cols="20" rows="10"></textarea> </td> </tr> <tr> <td align="center"> <input type="submit" value="שלח" /> </td> </tr> </table> and this is the JS: Code: <script type="text/javascript"> function chkfld(id) { if (document.getElementById(id).value == "" || "שדה חובה") { document.getElementById(id).style.backgroundcolor = "yellow"; document.getElementById(id).value == "שדה חובה"; } else { return true; } } </script> 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. Hi, I have added an validation script for Pizza menu. Validation working fine in all browsers except IE. When I working in IE8 it throws an error "length is null or not an object error in IE8". Please help me. See Java script code below: <script> function UnCheckRadios(radioButtonGroupName) { var formName = "frmOrder"; var form = document.forms[formName]; alert(form); var noOfRadioButtons=form[radioButtonGroupName].length; for(var x=0;x<noOfRadioButtons;x++) { chk=form[radioButtonGroupName] .checked=false; } } </script> PHP code: <input type="radio" id="<?=$subitem['subgroup_id'];?>_comboleft" name="<?=$subitem['subgroup_id'];?>_comboleft" value="<?=$subitem['id'];?>:Left Side" onclick="UnCheckRadios('<?=$subitem["subgroup_id"];?>_combowhole');"> |