JavaScript - Cannot Reference A Class
hey I want to get the href via attributes of this a tag
& then this href to be set to a variable Similar TutorialsHello, I am new with Javascript and running into this problem that I don't understand. I define a base class that only contains an array "elements", and a derived class that contains nothing more (for simplicity): Code: function baseClass() { this.elements = new Array; } function derivedClass() { } derivedClass.prototype = new baseClass; Then I create two instances of the derived class, and add two elements in each: Code: a = new derivedClass(); a.elements.push("A"); a.elements.push("B"); b = new derivedClass(); b.elements.push("C"); b.elements.push("D"); When I examine the contents of these arrays, I see that both a.elements and b.elements contain {"A","B","C","D"} ! I.e. as if the two arrays are in fact the same array! But these are two separate instances of the class, I expect two separate arrays. Note that if instead I use the base class: Code: a = new baseClass(); a.elements.push("A"); a.elements.push("B"); b = new baseClass(); b.elements.push("C"); b.elements.push("D"); then I get a.elements = {"A","B"} and b.elements = {"C","D"}, as I would expect. Could someone explain to me the problem with using the derived class? Thank you, Stephanos I'm working on making a searchable javascript and DOM reference...A chm like what php has. I mainly need it for myself because I don't always have access to the net. I was wondering if anyone would like to contribute? Hi Experimenting. Trying to add a simple onclick event via onload, but I can't get it right? This works: Code: function checkStatus(box){ if(box.checked != box.defaultChecked){ alert("box status has changed"); } } HTML <input type="checkbox" name="mycheckbox" id="mycheckbox" value="&cost=free" onclick="checkStatus(this)" /> This does not: Code: <input type="checkbox" name="mycheckbox" id="mycheckbox" value="&cost=free" /> window.onload = function (){ var mybox = document.getElementById('mycheckbox'); mybox.onclick = checkStatus ; //how to get this to work?? //none of the following work //mybox.onclick = checkStatus; //this calls the function but I don't have a box ref //mybox.onclick = checkStatus(); //mybox.onclick = checkStatus(this); //mybox.onclick = checkStatus(mybox); } LT Hi! I'm working on a JSP based project. On myJsp1.jsp, I open a new window using window.open and store reference in a variable myWin like myWin = window.open(.........); from here i submit the form to myJsp2.jsp. In this file, I want the reference myWin to close the opened window. What I'm doing while submitting form is: myWin = window.open(.............); document.onlinePayStatusSummary.action ="myJsp2.jsp?action=forwardOnlinePayRequest&childWindow=" +myWin; document.onlinePayStatusSummary.submit(); I've read that this way JavaScript references can be passed in url. Now when I do getParameter in myJsp2.jsp as var winRef = "<%=request.getParameter("childWindow").toString()%>"; winRef.close(); I get JavaScript error that this winRef do not support the close() property. Any help? Hey, I was having some trouble with this, and couldn't seem to find anything similar anywhere. (I'm not sure it's possible). (I know- for a normal variable there are no pointers in JS.) Normally, you can get an object reference: Code: obj.a = {...}; var pointer = obj.a; //now, changes to pointer cause changes to obj.a However, I would really like to be able to get a reference to a "variable" defined with a setter: Code: obj.__defineSetter__("a",function(input){...}); var pointer = obj.a; //but now: pointer = "..."; //does absolutely nothing! (as expected) Anyone know a way to do this? (without using __defineSetter__ to create pointer). If you are wondering, this is what I would like to be able to do: Code: obj = { a:function(value) { obj.other=value; this.__defineSetter__("a",function(input){ //do something with input, depending on obj.other //reset obj.other //reset obj.a to its original definition }); return ? //return pointer to obj.a } } obj.a("...") = OtherFunctionOutput(); obj.a("...2") = OtherFunctionOutput2(); //etc... (This would be extremely useful in the context I'm working with. Basically, obj.a would be oscillating between a function that modifies some obj properties and a variable that can be set using cleaner syntax than is otherwise possible.) (The simple alternative would look like: ) Code: obj.a("...",OtherFunctionOutput()); (But, I'd really like to get the syntax described above working, if possible) Thanks for any help anyone! Hi everyone, Does anybody know where I can download a decent Javascript reference in eBook format ?? Hello, I'm working on a drag and drop HTML editor, in which blocks can be positioned. I need to build a controller which listens to mouse events and takes appropriate action (a state machine). The system is built using prototypes and objects. The Controller class looks like this (I removed some methods for simplification): Code: /** * Creates a controller for a document */ function Controller() { /** * Document which is controlled by this controller * @var Editor * @access private */ this.document = null; /** * Overlay over the complete document, starting at the same position as the document * @var HtmlElement * @access private */ this.overlay = null; /** * References to event handlers * @access private */ this.moveEventHandler = null; /** * Processes a mouse move in the viewport * @param Controller reference Substitution for 'this' * @param MouseEvent event */ this.handleMove = function(reference, event) { //@do stuff //Update selection region reference.document.getSelection().setRange(..); reference.document.getSelection().update(); return false; } /** * Replaces the current document with the specified document * @param Doc document * @post Event handlers are ready to go */ this.setDocument = function(document) { //Set document and overlay this.document = document; this.overlay = document.getOverlayContainer(); //Add event listeners to viewport this.moveEventHandler = new EventHandler(this, this.handleMove); if (this.overlay.addEventListener) { //W3C browsers this.overlay.addEventListener("mousemove", this.moveEventHandler, false); } else if (this.overlay.attachEvent) { //IE browsers this.overlay.attachEvent("onmousemove", this.moveEventHandler); } //Disable right mouse menu and browser text selection this.overlay.oncontextmenu = function() {return false;} this.overlay.onselectstart = function() {return false;} this.overlay.onmousedown = function() {return false;} } } //Event handler wrapper function EventHandler(reference, handler) { this.reference = reference; this.handler = handler; this.handleEvent = function(e) { this.handler(reference, e); } } The method 'handleMove' is entitled to handle a mouse move on the overlay. Because the 'this' keyword would not point to the Controller object I've written a wrapper according to the W3C EventListener interface (http://www.w3.org/TR/DOM-Level-2-Eve...-EventListener). This wrapper holds a reference to the object in which the method resides that's handling the event, so that the important 'document' attribute can be reached. This document holds the document that is being edited (it's of a custom type, and not to be confused with the document as in document.body) The problem I now have is as follows. IE doesn't seem to be able to work with event handlers following the EventListener interface, but just functions. I need to get the object's reference there as well though, but this can't be done using an anonymous function, as at the moment it will be run it will be in a different scope, and not be able to reach the controller any more. Just using a global holding that reference variable, a method I used before, is not sufficient, as there may be multiple instances of the editor running on the same page. I have no problems in FFox, Opera, and Safari. Just IE because it uses an alternative event listener model. Has anyone got an idea how to get around this problem? My question is commented in the script: Code: function Love(){ var req = { ring : 'gold', money : 'a lot', commitment : 'long-term' } this.loveReqs = function(){ return req; } } var you = new Love(); var details = you.loveReqs(); details.ring = "silver"; console.log(details.ring); var me = new Love(); var details = me.loveReqs(); console.log(details.ring); // why does this return gold and not silver if req is passed by reference and we already changed its value above and so it's pointing to the same memory position? Hi I'm trying to write a data checking function that after it completes should return the focus to the text box that was checked and highlight everything in it IF the value was unacceptable. Here is the function: Code: <script type="text/javascript"> function chkValidity(numToCheck) { if (isNaN(numToCheck) == true || numToCheck < 0) { alert("Please enter a number greater than zero"); numToCheck.focus() numToCheck.select() return false } } </script> And here are the lines of code that would call the function: Code: <input type="text" name="numBedrooms" size="3" maxlength="3" onblur="return chkValidity(this)" /> <input type="text" name="areaBedrooms" size="3" maxlength="3" onblur="return chkValidity(this)" /> <input type="text" name="numLivAreas" size="2" maxlength="3" onblur="return chkValidity(this)" /> <input type="text" name="areaLivAreas" size="3" maxlength="3" onblur="return chkValidity(this)" /> <input type="text" name="numServAreas" size="2" maxlength="3" onblur="return chkValidity(this)" /> <input type="text" name="areaServArea" size="3" maxlength="3" onblur="return chkValidity(this)" /> What I find happens is that the data checking works and the error mesage displays, but the focus does not return to the text box. Any ideas? Regards Jenny I've been looking for a reference to my situation for two days and i can't find any that are relevant enough. I'm trying to accept text as a URL for an image source. I then display that image in a form with the use of a <button type=button onclick=codeThatGeneratesImage > type thing. Code: function addImageToForm(formID) { //get a reference to the form var formElement = document.getElementById(formID); //get a reference to the element that contains the url var elementWithImageURL = document.getElementbyId("imageURLInput"); //get URL entered var imageURL = elementWithImageURL.getAttribute("value"); //create image element ---------------------------------------------------------------------------------- var newImage = document.createElement("img"); //reference the source using the url newImage.setAttribute("src", imageURL); newImage.setAttribute("name", "newImage"); //append the image to form formElement.appendChild(newImage); } i know that the bottom half works because i tried it with just a reference to an image directly and it worked. i can't figure out why most of the top part isnt working. any help would be much appreciated The goal is for selectedDay to be assigned the value of the system variable Mainpackage.subclass0.subclass1.firstDay and then incremented by two days. Mainpackage.subclass0.subclass1.firstDay needs to be unchanged. Important system variable in red. To be 'manipulated and used' variable in green. Even with an intermediary, third, dummy variable it doesn't work: Code: //Declarations and instantiations var systemDate = new Date(); var selectedDay = new Date(); Mainpackage.subclass0.subclass1.firstDay ; //Assignments and manipulations systemDate = Mainpackage.subclass0.subclass1.firstDay ; selectedDay = systemDate ; selectedDay .setDate( selectedDay .getDate()+2); //Logging console.log('Mainpackage.subclass0.subclass1.firstDay: ' +Mainpackage.subclass0.subclass1.firstDay +'\n' +'systemDate: ' +systemDate +'\n' +'selectedDay :' +selectedDay +'\n'); Console log is: Code: Mainpackage.subclass0.subclass1.firstDay: Tue Aug 24 2010 00:00:00 GMT-0400 (Eastern Daylight Time) systemDate: Tue Aug 24 2010 00:00:00 GMT-0400 (Eastern Daylight Time) selectedDay: Tue Aug 24 2010 00:00:00 GMT-0400 (Eastern Daylight Time) It doesn't work in my webapp : All variables change at the same time. I just started learning javascript, and it'd be cool if I could find some kind of javascript reference site similar to php.net/manual with a quick reference search. After looking through google for a long while, all I could find was tutorial sites or reference books with the only way to navigate them is through boring tables of contents. Does such a place exist? Or what's the next best thing?
I'm working on this website and some contents are set up in arrays. How do you refer variables to work with arrays. I need the correct syntax.
Image of the output: http://i.imgur.com/jqzhJxb.png What I'm trying to do, is pass an object by reference so that I can use it in other scripts, and allow the current script to change the object's value when appropriate. What's happening: It passes correctly, you can see that my var_dump of the object before the function call is 30. After the function call, it becomes 60. Also, it writes "now60" to the document as instructed. When I call the function the second time, it does nothing. No error, no repeat of writing now60 to the document, etc. And in the last var_dump, which is after the second function call - you can see that the value remained 60. Why? Thanks for your help! Code: PHP Code: var quickChallengeTimer = {timer:30}; var quickChallengeQuestion; var quickChallengeAnswer; var quickChallengeResponse; function quickChallenge(quickChallengeTimerfunc, quickChallengeQuestion, quickChallengeAnswer) { if (typeof quickChallengeResponse == 'undefined') { switch (quickChallengeTimerfunc.timer) { case 30: quickChallengeTimerfunc.timer = 60; quickChallengeResponse = 'undefined'; document.write("now60"); break; case 60: quickChallengeTimerfunc.timer = 120; quickChallengeResponse = 'undefined'; document.write("now120"); break; default: document.write("Error"); break; } } console.dir(quickChallengeTimerfunc.timer); } var_dump(quickChallengeTimer); quickChallenge(quickChallengeTimer); var_dump(quickChallengeTimer); quickChallenge(quickChallengeTimer); var_dump(quickChallengeTimer); Hi, I have this ajax routine... Code: function xhr_get(target_str,async){ var sync=true; if(async){sync=false;} var xhr = new XMLHttpRequest(); xhr.open('GET', target_str, sync); if(sync==false){ xhr.onreadystatechange = function () { if (xhr.status === 200) { try{ var ii =JSON.parse(xhr.responseText);} catch (exception) { } if(ii){ return ii; }else{ alert(xhr.responseText); return false; } } else { alert(xhr.status+' '+target_str);return false; } }; xhr.send(null); }else{ xhr.send(null); try{ var ii =JSON.parse(xhr.responseText);} catch (exception) { } if(ii){ return ii; }else{ alert(xhr.responseText); return false; } } } now if I alert(ii) on success the data I am looking for (specifically ii.content) shows up in the alert as expected however when calling from another javascript function, ii is false ???? please explain, Code: function call_change_val(fld,vm_id){ var str='?_f=load_edit_fld&_ctl_fld='+fld+'&vm_id='+vm_id+'&fld='+fld+'&width=80'; i = xhr_get('ajax/val_main_loader.php'+str,true); ////////////////////// alert(i); or alert(i.content) here both give be a blank popup///////////////// showdiv('c_change_'+fld); setih('c_change_'+fld,i.content); } I expected alert(i) to say Object or similar, getting nothing Hello; I have a situation where an image tag is nested in an anchor tag set. The anchor is assigned an id and is assigned a click/onclick event listener. The anchor id corresponds to a list of objects in an array. In practice, the image tag is receiving the event. The code does setAttribute in another elements img tag src attribute. The image tag receiving the click event, (and passing it to the anchor tag) is event.target. (or event.srcElement, in the case of I.E.) My Question: What I want to know is how to reference the event.target parent element, the anchor tag elements Id attribute. Code: sample anchor/img tag set: <a style="font-family:Arial, Helvetica, sans-serif;color:#cccccc" id="An 1" alt="An 1" href="javascript:"><img style="border:1px solid;border-color:#cccccc" src="WC_port/windows/img//an_1.jpg" width="100" height="131" /><br /><br />An 1</a> I see the double slash in the img src path attribute. It is working as is in test browser: Firefox ( so far) This is in development stages. Later, I will assign the elements a css class rule. in my code, event.target.src has a usable value (src attribute of the img tag) It does not have a usable value for event.target.id (id attribute of the anchor tag) I am doing it this way so in the absence of javascript, the anchors href attribute defaults to a non scripted value. Thank you for time and attention JK İ want to use this code but when the page opens, I get a null reference error. When I open the page a second time, this error doesn't occur. I understand when the site caches, this error doesn't occur. The error comes from tb_show function. My code: <script type="text/javascript"> function writeCookie(CookieAdi) { var dtGun = 1 var strValue = "1" if (dtGun == null || dtGun == "") dtGun = 365; var d = new Date(); d.setTime(d.getTime() + (dtGun * 24 * 60 * 60 * 1000)); var zt = "; expires=" + d.toGMTString(); document.cookie = CookieAdi + "=" + strValue + zt + "; path=/"; } function readCookie(cookieadi) { var c = document.cookie; if (c.indexOf(cookieadi) != -1) { s1 = c.indexOf("=", c.indexOf(cookieadi)) + 1; s2 = c.indexOf(";", s1); if (s2 == -1) s2 = c.length; strValue = c.substring(s1, s2); return strValue; } } writeCookie('OnerFacebook'); if (readCookie('OnerFacebook') != 1) { tb_show('', 'http://www.mobilyala.com/OnerFacebook/?KeepThis=true&TB_iframe=true&height=500&width=300&modal=true', ''); } </script> What should I do for it? I am running some javascript code which generates a popup window associated with a spell checking program. The way the program works, is that it takes the text out of a text field (passed as an object), spell checks the string, then puts it back into the text area field. My text area is located within a flash form, and I am having trouble pointing to it. I am sure my spell checking program is working, as it works fine if I point to an html text area. Do I have to do something special to point to a flash form object? Here is my code: Code: <!--- Source the JavaScript spellChecker object ---> <script language="javascript" type="text/javascript" src="../Spellchecking/spellerpages-0.5.1/speller/spellChecker.js"> </script> <!--- Call a function like this to handle the spell check command ---> <script language="javascript" type="text/javascript"> function openSpellChecker() { // get the textarea we're going to check <!--- pointer to text area ---> var txt = window.activity.Summary; // give the spellChecker object a reference to our textarea // pass any number of text objects as arguments to the constructor: var speller = new spellChecker( txt ); // kick it off speller.openChecker(); } </script> Also, here is my text area: Code: <cfform format="flash" id="activity1" height="#formheight#" width="100%" style="#formstyle#" timeout="3600" wmode="transparent" name="activity" onLoad="#initVars#; onFormLoad();"> <cftextarea name="Summary" id="Summary" html="yes" maxlength="1000" tooltip="Summarize your entry here. The field has a 1000 character limit. This summary is included in the generated End of the Week reports." onChange="submitTemporary('Summary', Summary.text);requiredContent('summary');" onFocus="if(detailsBox.height>60){detailsBox.height=60;summaryBox.height=220;}"></cftextarea> </cfform> Any help on this issue would be much appreciated. Thanks, AeroNicko I am confused about what the return keyword is actually returning when returning an object, a primitive, or a function. My confusion is compounded by the fact that I'm not sure if a function is an object or not. According to the book JavaScript Programmer Reference it is: "All functions in JavaScript are first class objects , meaning they can be passed around like any other object reference. In fact, regardless of how they are created, functions are instances of a global object named (aptly) Function." However, someone else states that a function is not an object. An object is a set of primitives and references. A function is executable code. Functions become objects through the use of the new operator. Yet, in the book I mentioned, it says you don't need the new keyword to execute the function as an object, as it already inherits from the object Function when the function keyword is used: Code: function functionName([argname1 [, ...[, argnameN]]]) { statements; } So there's one source of contradiction. Now the bigger issue is what is going on when the return keyword is used. Notice the Validation() function returns an object as its last expression. This technique is common, where you return an object which contains functions in form of object notation. I believe this is done so that we create a closure so that when the intepreter exits the Validation() method, since we created a closure by returning an object, which contains the inner functions addRule and getRule, the local variables of Validation() are not destroyed, given that we can reference them through the two inner functions that make use of the local variables of the outer function. So when we use the return keyword on an object literal, and then exit the function, when we call one of the inner functions as we do later: Code: var rule = $.Validation.getRule(types[type]); essentially getRule() is called, passes an argument, which is received by the inner function as parameter we call name: Code: getRule : function(name) { return rules[name]; } First, note that the return {} is written in object notation, therefore making getRule a local variable and, thus, private function only accessible through the namespace of Validation(). Validation() declares the rules local variable and because of the closure, we can access the rules local variable through the getRule() inner function. *****Here's the part that really thows me off. We return rules[name]. So let's say name is equal to email. This is an associative array so email (held in name) is a property of rules. So here we return the object's property: Code: return rules[name]; And then assign it to a local variable called rule: Code: var rule = $.Validation.getRule(types[type]); So when we return an object rules[name], do we return a reference to an object or a value? In other words, by returning rules[name], where name is equal to email, are we then returning a reference to the following object literal: Code: email : { check: function(value) { if(value) return testPattern(value,".+@.+\..+"); return true; }, msg : "Enter a valid e-mail address." } And if we are returning a reference, by returning a reference, are we essentially pointing to this object when we assign it to rule? In other words, the variable rule is just pointing to the object literal? And is that the reason we can then access the check function or msg local variable through rule using dot notation, because rule points to the email object literal? Now the ultimate brain twist for me is that if a function is an object, then why when return a function, it returns a value, such as a boolean, if an object only returns a reference and not the value? Code: //Validation is a local variable as it is in a self-executing anonymous function. The purpose of the said anonymous function is to pass the jQuery object as a parameter $ so the $() function will be in scope of the anonymous function and not interfere with other libraries that make use of the same function technique - in the global scope. (function($) { var rules = { email : { check: function(value) { if(value) return testPattern(value,".+@.+\..+"); return true; }, msg : "Enter a valid e-mail address." }, url : { check : function(value) { if(value) return testPattern(value,"https?://(.+\.)+.{2,4}(/.*)?"); return true; }, msg : "Enter a valid URL." }, required : { check: function(value) { if(value) return true; else return false; }, msg : "This field is required." } } var testPattern = function(value, pattern) { var regExp = new RegExp("^"+pattern+"$",""); return regExp.test(value); //The test() method is built into javascript } return { addRule : function(name, rule) { rules[name] = rule; }, getRule : function(name) { return rules[name]; } } } /* Form factory */ var Form = function(form) { var fields = []; $(form[0].elements).each(function() { var field = $(this); if(field.attr('validation') !== undefined) { fields.push(new Field(field)); } }); this.fields = fields; } Form.prototype = { validate : function() { for(field in this.fields) { this.fields[field].validate(); } }, isValid : function() { for(field in this.fields) { if(!this.fields[field].valid) { this.fields[field].field.focus(); return false; } } return true; } } /* Field factory */ var Field = function(field) { this.field = field; this.valid = false; this.attach("change"); } Field.prototype = { attach : function(event) { var obj = this; if(event == "change") { obj.field.bind("change",function() { return obj.validate(); }); } if(event == "keyup") { obj.field.bind("keyup",function(e) { return obj.validate(); }); } }, validate : function() { var obj = this, field = obj.field, errorClass = "errorlist", errorlist = $(document.createElement("ul")).addClass(errorClass), types = field.attr("validation").split(" "), container = field.parent(), errors = []; field.next(".errorlist").remove(); for (var type in types) { var rule = $.Validation.getRule(types[type]); if(!rule.check(field.val())) { container.addClass("error"); errors.push(rule.msg); } } if(errors.length) { obj.field.unbind("keyup") obj.attach("keyup"); field.after(errorlist.empty()); for(error in errors) { errorlist.append("<li>"+ errors[error] +"</li>"); } obj.valid = false; } else { errorlist.remove(); container.removeClass("error"); obj.valid = true; } } } /* Validation extends jQuery prototype */ $.extend($.fn, { validation : function() { var validator = new Form($(this)); $.data($(this)[0], 'validator', validator); $(this).bind("submit", function(e) { validator.validate(); if(!validator.isValid()) { e.preventDefault(); } }); }, validate : function() { var validator = $.data($(this)[0], 'validator'); validator.validate(); return validator.isValid(); } }); $.Validation = new Validation(); })(jQuery); Thanks for any response. |