JavaScript - Onchange Scope
Hi there - this seems like it should be an obvious problem - can anyone spot it?
I have an object, declared this way: Code: var FK_gid = new picChooser('FK_gid', FK_gidArray); FK_gid.init(); and a select group like this: Code: <select id = "FK_gid" name = "FK_gid"> <option value="none" selected="true" >None</option> <option value="335" >pics/zoobins.jpg</option> etc. etc. </select> picChooser in construction sets the onchange of the select group like this: Code: this.list = document.getElementById('FK_gid'); this.list.setAttribute("onchange", "FK_gid.displayImage();"); and the object's displayImage(); is like this: Code: this.displayImage = function () { this.clearImage(); if (this.list.selectedIndex != 0) { pic = new Image(); pic.src = this.reformat(this.list.options[this.list.selectedIndex].innerHTML); img = document.createElement("img"); img.src = pic.src; this.preview.appendChild(img); } } But whenever I choose something else off the list I get this error message: Code: TypeError: Result of expression 'FK_gid.displayImage' [undefined] is not a function. It's bizarre because when I type FK_gid.displayImage(); into Safari's dynamic console the function works perfectly... Any ideas? Thanks Edd Similar Tutorialshi all ~ this is my code, when i change the first checkbox , i want to change the var theSame, but it seams doesn't change in if(theSame == 1) ; but it changes in alert("b"+theSame) , it's queer, how to handle this ? 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> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ var theSame = 1; $("input[name='thesame']").change(function(){ theSame = $(this).is(":checked") ? 1 : 0; alert("a"+theSame) }); if(theSame == 1){ $(".check_list input").change(function(){ alert("b"+theSame) }); } }); </script> </head> <body> <input type="checkbox" name="thesame">same <br> <div class="check_list"> <input type="checkbox" name="son">ppp <input type="checkbox" name="son">ppp <input type="checkbox" name="son">ppp </div> </body> </html> I don't really understand why a.d() fails in the following, or rather why a.d can't access local vars in a, or how to rewrite this so that it can PHP Code: window.a = (function () { var b = '<br>hello '; var c = function (){ document.write(b+'from c') // in this scope we can access the local vars of a }; c() // this will work and write hello from c document.write(b) // this will work and write hello from b return{c:c} })(); a.d = function () { document.write(b+'from d') // even though as far as I can tell I have added d to the object a, } // this still can't access the local vars of a... why not? how can I change that? a.d() // doesn't work :( a.c() // this works too because we returned c in a's return statement I have a popup in one of my pages which is populated via AJAX call with a list of click-able options, this is all good, however I am now trying to display a javascript tree in the popup but it can not seem to 'see' the javascript routine that creates the tree, even if I hard code that into the popup itself, so the tree starts with d=new dTree() , and javasript is telling me that 'd' is undefined. the code works fine in a regular webpage but when pulled up in a AJAX generated popup it cant see squat? I tried parent.dTree() etc but to no avail. Is this because the javascript is loaded after the main page load via AJAX? if so is it accessible in anyway ? Recently I had an issue while trying to copy an array: I couldn't understand why modifying the new array caused modifications in the old array Old Pedant cleared that up nicely for me in http://www.codingforums.com/showthread.php?t=240020 Now I'm trying to understand closures, and scope and all that fun stuff thanks to Venegal's great tutorial at reallifejs.com and I have the following: Code: <script> window.USER = (function(){ var Employees = [['Alex',1,'ft',1],['Olivia',2,'ft',1],['Brenda',3,'ft',1],['Michael',4,'ft',1]]; var info = ['Start String']; var Setup = function(){ } return{ CheckLogin : function(login){ this.info = Employees[login]; }, Reset : function(){ }, info:info, Emp:Employees }; })(); </script> And I think I got all the kinks worked out, but there was one thing that I don't understand... Based on my other thread I expected the modification of USER.info to overwrite values in USER.Emp Don't get me wrong, I didn't want that to happen, I am just confused as to why it didn't I used the following buttons to test the values of USER.info and USER.Emp but again, writing to USER.info did not overwrite anything in USER.Emp.... Code: <script> document.write('<button onclick="alert(USER.info)">USER.info read</button>'); document.write('<button onclick="USER.info=\'Test String\'">USER.info write</button>'); document.write('<button onclick="alert(USER.Emp)">Employees read</button>'); document.write('<button onclick="USER.CheckLogin(0)">Check Login</button>'); </script> So what I guess I'm asking is why? Or maybe: what is happening here, and how does it differ from my last issue? Was it maybe a scope issue? Or maybe something more sinister...? I am doing project exercises from a JavaScript book for a college class. I am creating a brand new .html document for each project. I was under the impression that each unique page name would have its very own cookie scope. But to my surprise it seems adding/loading cookies using 'document.cookie' doesn't assign new cookies to each page. I am seeing that when I try to load document.cookie in new .html pages there are cookies that were already created in past pages in the document.cookie property/string. So whats the 'default' scope of a document cookie. Do I have to set the domain property to get unique cookies for each .html page I create? Thanks for the help. Edit: Okay, it seems that cookies have a default scope of the folder your .html page resides in and all sub-folders that your page resides in. I moved my project folder so that it was a sibling of my projects folder and it got its own cookies that way. I am writing a rather large bookmarklet. For this bookmarklet I would like to have some user-defined variable values. My idea for this is a bookmarklet code something like this Code: var MY_var = "my value"; (function(){ /* usual loading of bookmarklet script file */ var s=document.createElement('script'); s.type='text/javascript'; s.src='https://myhost.com/path/to/my.js; document.getElementsByTagName('head')[0].appendChild(s); })(); However I can't access the variable MY_var in the bookmarklet script file "my.js". Is there any way I can change the bookmarklet so that I can access MY_var in my.js? I have devised the following constructor based loosely on the observer pattern Code: Observer = function (ConditionIsTrue , codeToExecute){ var observer = this , ConditionWasMet = false , CheckIfReady = function () { if (ConditionIsTrue()) { if(!ConditionWasMet) codeToExecute(); ConditionWasMet = true; } else { if (ConditionWasMet) ConditionWasMet = false; } }; Loop.call(observer , CheckIfReady) observer.speed(1) }; It works fine, no problems that I know of... But the most interesting thing happened when I attached it to my lib and ran it through the http://closure-compiler.appspot.com/home compiler Code: $['Observer'] = function (//...etc... For the first time the compiler has added something to my global scope Code: var i=!1; window.$=function(){//...etc... ... Observer:function(j,k){var h=i;Loop.call(this,function(){j()?(h||k(),h=!0):h&&(h=i)});this.speed(1)} } })(); Can someone explain to me why the var ConditionWasMet had to be exported to the global scope? Was it already in the global scope? That would confuse me considering the observer can be called from multiple instances without conflict... But I don't want any surprise conflicts jumping out at me later, I appreciate the consideration. I don't even know where to begin with this one. I don't know the terminology for what I am trying to do here, and the sample code is too big and cluttered to post. So I put together the following to illustrate the structure of the object that I am trying to overcome. I have a method chain within an object, and I need to override one of the methods, but when I do so I loose access to the private methods and properties of it's containing object... I googled this for several hours, and the best that I can come up with is that I need to somehow use call() to access the scope of another object. But I don't understand call() or apply() at all, and I've read many tutorials on those... Code: window.oModule['Report'] = (function(){ var _privateProp1 = '' , _privateMethod1 = function(){ // ... } , _publicMethod1 = function(){ // ... } , _publicMethod2 = (function(){ var _sub_privateProp1 = '' , _sub_privateMethod1 = function(param1,param2){ // ... } , _sub_publicMethod1 = function(){ // ... } , _sub_publicMethod2 = function(start , end){ // I need to replace this method from somewhere else var _neededValue = ''; for(var i = start ; i<end ; ++i) { // ... _neededValue += _sub_privateMethod1(arg1,arg2) } return _neededValue; } ; return{ '_sub_publicMethod1' : _sub_publicMethod1 , '_sub_publicMethod2' : _sub_publicMethod2 } })() ; return{ '_publicMethod1' : _publicMethod1 , '_publicMethod2' : _publicMethod2 } })(); alert(oModule.Report._publicMethod2._sub_publicMethod2(1,5)) // This works fine oModule.Report._publicMethod2._sub_publicMethod2 = function(start,end){ // Doing this modifies the output of all expressions that already call the sub method (which is what I need) var _neededValue = ''; // ... return start+end } alert(oModule.Report._publicMethod2._sub_publicMethod2(1,5)) // This will alert 6 (as intended) oModule.Report._publicMethod2._sub_publicMethod2 = function(start,end){ // Doing this modifies the output of all expressions that already call the sub method (which is what I need) var _neededValue = ''; for(var i = start ; i<end ; ++i) { // ... different set of instructions _neededValue += _sub_privateMethod1(arg1,arg2) // This line causes an error: _sub_privateMethod1 is undefined } return _neededValue } Let's say I'm defining an object and I want the constructor to take one input and ten save it. I'd like to do something like this: function apple(color) { this.color = arguments.color; } But of course that doesn't work because arguments isn't a scope. My question is, is there a scope I can use. What I've been doing instead is this: function apple(new_color) {this.color = new_color;} But that just seems less than perfectly pretty. Hello, I am trying add some animation effects to a navigation button and am having some problems with my code. I am using setInterval(); and the problem came with trying to clear it using clearInterval(); if i have this code then it seems to clear it fine: Code: var i = 21; function w(){ document.getElementById("homebtntop").style.height = i + "px"; i--; } function c(){ if(i<=6){ window.clearInterval(t); } } function r(){ t = self.setInterval("w()",15); } function slideIn(){ t = self.setInterval("w()",15); clearInterval(t); } but if i then try to call it from inside a function c(); it doesn't work: Code: var i = 21; function w(){ document.getElementById("homebtntop").style.height = i + "px"; i--; } function c(){ if(i<=6){ window.clearInterval(t); } } function r(){ t = self.setInterval("w()",15); } function slideIn(){ t = self.setInterval("w()",15); clearInterval(t); } Any ideas? i am sorry if my code makes no ssense or is badly formatted, this is my first time with javasript. Thank you. This is a bit of a strange one. I have been trying to call a function in a child object from the parent object but the child seems to be going out of scope in onbeforeunload function. These function calls work outside of a onbeforeunload, so it only fails when called in onbeforeunload. I can fix it by making the child object a global but I was trying to avoid that. Anyone know why my childobject is out of scope when called in onbeforeunload? Notice I call that same function in windows onload event and it works fine. Here is the code (I have simplified as much as possible to just show the error): Code: <html> <head> <title>Broken Page</title> <script language="javascript" type="text/javascript"> var myparent; function windowLaunch() { myparent = new parent(); myparent.getchildvalue(); window.onbeforeunload = myparent.getchildvalue; } function parent() { this.mychild = new childobject("myinput"); this.getchildvalue = function() { var tmpval = this.mychild.returnvalue(); }; } function childobject(thename) { this.myprop = thename; this.returnvalue = function() { return (document.getElementById(this.myprop).value); }; } </script> </head> <body id="thebody" onload="windowLaunch();"> <div id="outerdiv"> <span title="This Input Box">My Input:</span><br /> <input id="myinput" style="width: 290px"/> </div> </body> </html> Question: if I declare a variable in on js fiile, is this available to another js file that is loaded? Answer: yes, it's available (unless inside of a function or something) BUT: does it matter WHERE I declare this variable?? Let's say, I have the following in my HTML file: <script src="script/main.js"></script> And then at the very bottom of my HTML page before the </body> tag I have: <script type="text/javascript">var myvariable = "Sample Data";</script> So, is myvariable available to main.js? In simple tests I've done, yes it does seem to be available But... what if I have a lot of other js code running in between Does this change anything? Thanks OM Hi all, I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me. I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself. I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time. Here's the code: Code: displayFeed: function(responseData) { this.bodyEl.innerHTML = "xxxx"; // I can see this var responseDoc = Presto.Util.parseXml(responseData); var items = Ext.DomQuery.select("/rss/channel/item", responseDoc); items.each(function(item, bodyHTML) { var rssTitle = Ext.DomQuery.selectValue("/title", item); var rssDescription = Ext.DomQuery.selectValue("/description", item); var rssLink = Ext.DomQuery.selectValue("/link", item); // but this results in an undefined error this.bodyEl.innerHTML = '<a href="' + rssLink + '">' + rssTitle + '</a><br/>'; }); // end of items processing } This is a fragment of the code from my script. The first access of "this.bodyEl.innerHTML" works fine, but the second access in the items.each loop doesn't and I get an undefined variable error. Is this a scoping problem, and if so how is it best solved. Thanks in advance, Innes (NZ) Hey everyone, I wanted to write my own script for a fade-in animation, since the ones I have found have got too many options or need some framework, which makes them unnecessarily big. I wanted to learn too. Unfortunately, the code didn't work as I wanted, and I commented some things so as to find out what's happening. The only function called from outside is fadeIn with a string as argument (in the example, this string is: d1296668690535). This is the code: Code: var fadems = 500; // Anim. duration in milliseconds var fps = 20; // Frames per second function fadeIn(elemId){ var frames = fadems/1000 * fps; var delay = 1000 / fps; var incrOp = 1 / frames; //document.getElementById(elemId).style.zoom = '1'; setOp(elemId, 0); for(i=1; i<=frames; i++){ debugOutLn("(fadeIn for) elemId = " + elemId); setTimeout("setOp(" + elemId + "," + incrOp*i + ")", delay*i); } } function setOp(elemId, val){ debugOutLn("(setOp) elemId = " + elemId + "; val = " + val); // document.getElementById(elemId).style.opacity = val; // document.getElementById(elemId).style.filter = 'alpha(opacity = ' + val * 100 + ')'; } Code: function debugOutLn(str){ document.getElementById("debug").innerHTML += str + "<br />"; } And this is the text it outputs (on Opera 11.01): Code: (setOp) elemId = d1296668690535; val = 0 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (setOp) elemId = [object HTMLDivElement] ; val = 0.1 (setOp) elemId = [object HTMLDivElement] ; val = 0.2 (setOp) elemId = [object HTMLDivElement] ; val = 0.30000000000000004 (setOp) elemId = [object HTMLDivElement] ; val = 0.4 (setOp) elemId = [object HTMLDivElement] ; val = 0.5 (setOp) elemId = [object HTMLDivElement] ; val = 0.6000000000000001 (setOp) elemId = [object HTMLDivElement] ; val = 0.7 (setOp) elemId = [object HTMLDivElement] ; val = 0.8 (setOp) elemId = [object HTMLDivElement] ; val = 0.9 (setOp) elemId = [object HTMLDivElement] ; val = 1 Why is an object reference assigned to what was previously a string? Thanks for the help! Code: <input type = "text" style ='display:none;' onchange="display_data_from_server(this.value)"/> Value inside that input is cahanged from js. Is there any reason that onchange would not happen ? i mean, it does not. Hi folks. I'm working on a calculator and need to use the 'onchange' function. Basically, the user selects the year (id=taxYear) and once the year is select (default is 2008) this year will appear in 2 different lines of the page under 2 seperate ID's(ageYear & totalYear). I've looked at a few example of the function but I'm still not sure how to approach it. At the moment the year changes once I hit the 'calculate' button but the onChange would obviously offer a better alternative with the date changing once 'taxYear' is changed. here is the script; Code: //check the year var taxYear = document.getElementById('taxYear').options[document.getElementById('taxYear').selectedIndex].value; document.getElementById('ageYear').innerHTML = taxYear; document.getElementById('totalYear').innerHTML = taxYear; Here is the jsp; Code: <tr> <td align="left" width="203" colspan=""><p> Your Tax Year: </p></td> <td align="left" > <s:select name="taxYear" id="taxYear" list="#{'2008':'2008', '2009':'2009'}" theme="simple" />* </td> </tr> <tr> <td align="left" width="203"><p> Age at December 31st <span id="ageYear"></span></p></td> <td align="left" colspan="1"> <s:textfield name="age" id="age" theme="simple" cssClass="text" value="30" /> * <div id="errorage" class="warningmessage" style="display:none"> Please enter your Age to proceed. </div> </td> </tr> <tr> <td colspan="2" class="basicboldtext"> <br/> The total pension contribution you can make for year <span id="totalYear"></span> is €<span id="totalTax2"></span> <br/> </td> </tr> Appreciate any help on this! I have a onChange value
Code: var people = [ ["Timothy Conner", "1999-Present", "Age: 12", "Male", ""], ["Andrew Conner", "1992-Present", "Age: 19", "Male", ""] ]; var how = "Brothers"; function find() { if(document.getElementById("name").value == people [0] [0]) { document.getElementById("desc").value = people [0] [1] + " " + people [0] [2] + " " + people [0] [3]; } if(document.getElementById("name").value == people [1] [0]) { document.getElementById("desc").value = people [1] [1] + " " + people [1] [2] + " " + people [1] [3]; } document.getElementById("relateb").value = document.getElementById("name").value; } Code: Name: <input type="text" id="name" value="" onChange="find()"/> So for it to proses a name you must click out of a box is ther a way to make it instead of when you click out of it, it would immidiatly change? I'm trying to figure out how to call multiple functions within the same onchange attribute, associated in the same select object. I have a drop-down menu in which I can select MN, WI, and Other. I've worked it now so that when I select MN, a new drop-down menu appears in which I can select one of MN's Counties. I want to be able to do the same with WI and Other, but my code is only calling MN. Here it is: Code: <html> <head> <script="text/javascript"> function showMN(select) { select.form.MN.value=""; // reset the text box value document.getElementById("MNBox").style.display = select.value == "MN" ? "inline" : "none"; } function showWI(select) { select.form.WI.value=""; // reset the text box value document.getElementById("WIBox").style.display = select.value == "WI" ? "inline" : "none"; } function showOther(select) { select.form.otherState.value = ""; // reset the text box value document.getElementById("otherBox").style.display = select.value == "Other" ? "inline" : "none"; </script> </head> <body> <select name="state" onchange="showMN(this);showWI(this);showOther(this)"> <option value="" selected="selected">Choose...</option> <option value="MN">MN</option> <option value="WI">WI</option> <option value="Other">Other</option> </select><font color="red">*</font> <span id="MNBox" style="display:none"> County: <select name="MN"> <option value="" selected="selected">Choose...</option> <option value="List of MN Counties">List of MN Counties</option> </select><font color="red">*</font> <span id="WIBox" style="display:none"> County: <select name="WI"> <option value="" selected="selected">Choose...</option> <option value="List of WI Counties">List of WI Counties</option> </select><font color="red">*</font> <span id="otherBox" style="display:none"> <input type="text" name="otherState" placeholder="Enter state here"/><font color="red">*</font> <input type="text" name="otherCounty" placeholder="Enter County here"</span> </body> </html> Am I even close? Hi I'm a newbie. Please help me. I'm using Joomla. I've got a dropdown which reads the filename from the database. When the user selects it I want an onchange event to open the pdf. I've been at it for 2 days now. Code: <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("metnet", $con); $sql="SELECT * FROM newsletter"; $result = mysql_query($sql); echo "<form method='post'>"; $dropdown = "<select name='sname' onChange='location(this.form.sname)' >"; while($row = mysql_fetch_assoc($result)) { $dropdown .= "\r\n<option value='{$row['fpath']}'>{$row['fpath']}</option>"; } $dropdown .= "\r\n</select>"; echo $dropdown; ?> HI, i know very little about javascript, just enough to get me into trouble actually lol. Here is what im working with. I have a custom Instant messenger for members. It uses embed object macromedia as well as javascript to diplay the window and send messages. What i want to do is simply add an onchange that when one person is typing it shows they are typing (ie xxxxx is typing....) My experience is in php and html and i looked thru the script and the javascript functions but im not sure what im looking for exactly. Do i need to have access to the swf or fla file and be able to edit them to do this? I dont see any form inputs or i would know exactly where to put the onchange lol. Im guessing the input is in the swf or fla file not sure how that works. what im guessing is that in the embed or the object tags (ill play with it) i can put something like Code: document.write('test on change\n'); i think i need to wrap that in doc write script type=javascript in quotes so it parses. If i can get that text to show up inside the IM where i want it then i can try to figure out how to set focus on box and recongize onchange and do some testing. I think i might even be able to doc write the onchange command but not sure. Thanks |