JavaScript - Passed By Reference - Function Fails On Second Call
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); Similar TutorialsI know I have a thread about the sorting function I'm about to post, but this problem doesn't deal with the sorting itself, but rather the fact that a variable is not passing. The code below is the relevant part to an autosuggest feature. The variable that isn't being passed is "firstValidIndex". It is being set appropriately, but when it is used in "sortArray()", its value is 0. Code: // here we must check to see if where the string matched was at the beginning of a string inside this.aNames // firstValidIndex is the first index where the char is at the beginning of a string var firstValidIndex; loop1: for(var j in firstIndices) { loop2: for(var k in allOccurrences) { if(allOccurrences[k] == firstIndices[j]) { firstValidIndex = firstIndices[j]; aList.push(this.aNames[i]); ctr++; break loop1; break loop2; } } } function sortArray(a,b) { var lca = a.toLowerCase(); var lcb = b.toLowerCase(); var lco = str.toLowerCase(); var diff = lca.indexOf(lco,firstValidIndex) - lcb.indexOf(lco,firstValidIndex); // some debugging code here alert("Comparing "+lca+" with "+ lcb+"\nDiff:"+diff+"\nFirst Valid Index: "+firstValidIndex); if ( diff < 0 ) return -1; if ( diff > 0 ) return 1; return 0; } aList.sort(sortArray); Hi all, I have a newbie question. I have just started working with javascript and would appreciate some guidance. I have a webpage and there are products for sale on it(this is not live it is merely being used as practice project). Beside each product is a description a price and an 'add to cart' button. My cart is simply a div with an id of 'cart' and it has a text box within it. I need the product name to be displayed within the div (this, I have working), I also need to display the product price in the text box once the button(add to cart ) for that particular product has been pressed. Also when the button for another product is pressed, I want the cost/value for that product to be added to the other value and displayed in the text box in the cart div... I apologise for rambling on but this is the best way of me explaining my needs.... Here's where i am right now.. The HTML snippet Code: <div id ="cart"> <p><img src="images/shopping-cart.png" alt ="cart"/>Your Cart</p> <div id="sum"><!--(this is the div where the total goes)--> <input type="text" id="total" value="0" /><p>€ Your Total <input type="reset" value = "reset" /></p> </div> </div> <h2 id ="black">Blackcurrent<br /></h2> <p>€ 12.00 <input type = "submit" value ="add to cart" onClick = "shoppingCart('Blackcurrent',12)" /></p> And the javascript: Code: alert ("working"); function shoppingCart (itemName,itemValue) { /* var thePrice = Number(itemValue); return thePrice;*/ document.getElementById ("cart").innerHTML += itemName + "<br/>"; document.getElementById('total').value = Number(document.getElementById('total').value) + itemValue; } I hope i have posted correctly and am aware that i have only posted a segment of the HTML.. Please let me know if you need any more code or info.. Thanks a lot in advance for any help... Hi, New to JS. Have ordered some new books, but need to get somethings going in the mean time. What I wanted to do is to link to a new page having a date range input in the form of 6 text boxes, 2 sets of mm-dd-yy, from and to, where the upon loading the page box 1 of the from would auto focus and then auto tab and then post where php could take over on the server side. Setting up the form and the lay out, no problem. Auto focusing went just like expected using the following code, included because on the next step everything fell apart. [/CODE] <script type="text/javascript" > window.onload=function() { document.getElementById("input1").focus(); } </script> [/CODE] So then the wheels came off and in response, began to simplify what was trying to be done to find where the issues were. As far as I can get working is: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <script type="text/javascript" > window.onload=function() { document.getElementById("input1").focus(); } </script> <script type="text/javascript" > function myFunc() { alert("is this working"); } </script> </head> <body> <input id="input1" name="input1" type="text" onkeyup="myFunc()" maxlength="2" value="type a No." /> </body> </html> First issue with this: When I first get to the page everything is just as ordered. The focus is on the text box and the default value is "type a No." When I press a key onkeyup, I bring up the alert box with "is this working" in it. But when I refresh the page with the refresh button, after clicking the "ok" on the alert box, the character that was typed in is still displayed. If I use the link to the page, or the URL from the address bar, then the page reloads properly with the default value, "type a No". Question 1: How do you get the default textbox value using the refresh button as apposed to reloading the page using a link or from the address bar? Using Firefox 8.0 Second and more important at the moment: If I change the script to pass an argument to the function the script crashes. It does not pull up an alert box and freezes. My guess is that I'm doing something wrong on a concept level. NOTE: changed the default value of the text box to " ". Looked like to me there was an issue with the size specification and the default string length as you could only enter in a key stroke by highlighting the text and replacing it Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <script type="text/javascript" > window.onload=function() { document.getElementById("input1").focus(); } </script> <script type="text/javascript" > function myFunc(awe) { alert(awe); } </script> </head> <body> <input id="input1" name="input1" type="text" onkeyup="myFunc("123")" maxlength="2" value="" /> </body> </html> Question 2: can someone straighten me out with this? On my site I'm using an external (big) javascript file, in this external file there is a function with the following line in it: Code: function showslide(){ return(currentSlide); } In my main html file the external javascript file is loaded within the head section. This external file does a lot of other stuff besides returning a number. Now here is my problem.. Somewhere in my html file I need to call the showslide function. I tried doing that with this: Code: <script language ="Javascript" src="upload/3weg_slider.js"> document.write(showslide()); </script> But it doesn't return anything, when I place an alert line within the function it doesn't show up either. What am I doing wrong here? İ 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 wrote a script that creates 2 absolutely positioned divs, in perfect alignment, one on top of the other. I want to use javascript to manipulate the display property of each div to show one div at a time by toggling each div's display property between none and block with an onClick event handler attached to the link. This script works fine when the javascript function has no parameters, because the div id's are inserted directly into the getElementById function. When I say it works, I mean the div with id=cal2 displays onload, then disappears when the Show Calendar link is clicked. The div that appears in its place has a link that does the reverse when clicked. I want to create multiple pairs of overlapping divs that toggle their visibility, so I want to put parameters inside the functions that identify the specific pair of divs that need to be toggled per function call. When I try to use variables/parameters in the functions to insert specific div id's into getElementById, it does not work. PLEASE NOTE, the code below has div id's in green that don't have quotes of any kind. It still works in my firefox browser. I thought id's needed quotes, but it works without. I don't know why. The code below works, but has no parameters in the functions: Code: <!DOCTYPE html> <xhtml> <head> <title>Practice Calendar</title> <style type="text/css"> .practicecalendar { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #B3FF99; text-align: center; } .practiceschedule { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #99E6FF; text-align: center; } </style> <script type="text/javascript"> <!-- function showSchedule(){ document.getElementById('sch2').style.display = 'block'; document.getElementById('cal2').style.display = 'none'; } function showCalendar(){ document.getElementById('cal2').style.display = 'block'; document.getElementById('sch2').style.display = 'none'; } //--> </script> </head> <body> <div id= cal2 class='practicecalendar' style=' display: block; '> <p>Calendar</p> <p><a href='' onClick='showSchedule(); return false'>Show Schedule</a></p> </div> <div id= sch2 class='practiceschedule' style=' display: none; '> <p>Schedule</p> <p><a href='' onClick='showCalendar(); return false'>Show Calendar</a></p> </div> </body> </xhtml> When I add the information in red to the same script above, I get the script below that does not work. Code: <!DOCTYPE html> <xhtml> <head> <title>Practice Calendar</title> <style type="text/css"> .practicecalendar { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #B3FF99; text-align: center; } .practiceschedule { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #99E6FF; text-align: center; } </style> <script type="text/javascript"> <!-- function showSchedule( sch,cal ){ document.getElementById( 'sch' ).style.display = 'block'; document.getElementById( 'cal' ).style.display = 'none'; } function showCalendar( cal,sch ){ document.getElementById( 'cal' ).style.display = 'block'; document.getElementById( 'sch' ).style.display = 'none'; } //--> </script> </head> <body> <div id= cal2 class='practicecalendar' style=' display: block; '> <p>Calendar</p> <p><a href='' onClick='showSchedule( 'sch2','cal2' ); return false'>Show Schedule</a></p> </div> <div id= sch2 class='practiceschedule' style=' display: none; '> <p>Schedule</p> <p><a href='' onClick='showCalendar( 'cal2','sch2' ); return false'>Show Calendar</a></p> </div> </body> </xhtml> When I remove the single quotes from the blue code , it does not work either. Code: <!DOCTYPE html> <xhtml> <head> <title>Practice Calendar</title> <style type="text/css"> .practicecalendar { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #B3FF99; text-align: center; } .practiceschedule { position: absolute; top: 0px; left: 0px; margin: 0; width: 18em; background: #99E6FF; text-align: center; } </style> <script type="text/javascript"> <!-- function showSchedule(sch,cal){ document.getElementById('sch').style.display = 'block'; document.getElementById('cal').style.display = 'none'; } function showCalendar(cal,sch){ document.getElementById('cal').style.display = 'block'; document.getElementById('sch').style.display = 'none'; } //--> </script> </head> <body> <div id=cal2 class='practicecalendar' style=' display: block; '> <p>Calendar</p> <p><a href='' onClick='showSchedule( sch2,cal2 ); return false'>Show Schedule</a></p> </div> <div id=sch2 class='practiceschedule' style=' display: none; '> <p>Schedule</p> <p><a href='' onClick='showCalendar( cal2,sch2 ); return false'>Show Calendar</a></p> </div> </body> </xhtml> Thanks for reading all of this. Does anyone know what I'm missing? Hi, I am hoping I just need to be pointed in the right direction with this. I have Page1. When Page1 body onloads it uses Ajax to call PartA Within PartA I have a message board so members can write messages which will be sent to my database in PartA[1] and immediately posted for view on to PartA[2]. As I want to have my request to the server updating regularly I want to have PartA[2] on a timed loop to refresh - I do not need the content of PartA[1] to refresh. So the order of events would look like this: Page1 | onload call | v PartA / \ V V PartA[1] PartA[2] (loads once) (constantly refreshes) What I am not sure about is that I have <body> and <head> attributes in Page1 only. I have already used my body onload to call PartA (and can't use it to call PartA[2] before PartA has loaded anyway). I do not want the user to have to click a button or do anything to call up PartA[2]. So my question is how would I get PartA[2] to automatically load within PartA? I hope I have made this clear, but if I haven't let me know and I will try again. i keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> <p> <script type="text/javascript">// <![CDATA[ var metrics = { "mm" : 1, "cm" : 10, "m" : 1000, "inch" : 25.4, "foot" : 304.8 }; function convert(num, dec){ var val = document.getElementById("fromVal").value; if(isNaN(val)){ return } function roundNumber(num, dec) { var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec); return result; } document.getElementById("toVal").value = val * metrics[document.getElementById("fromSystem").value]/ metrics[document.getElementById("toSystem").value]; } var interval = null; function watchChanges(){ interval == null ? setInterval("convert()", 500) : clearInterval(interval); } // ]]></script> </p> <table> <tbody> <tr> <td><input id="fromVal" style="width: 100px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="fromSystem" onchange="convert()"> <option value="mm">millimeters</option> <option selected="selected" value="cm">centimeters</option> <option value="m">meters</option> <option value="foot">feet</option> <option value="inch">inches</option> </select></td> </tr> <tr> <td colspan="1" align="center">=</td> </tr> <tr> <td><input id="toVal" style="width: 100px;" type="text" disabled="disabled" /><select id="toSystem" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">meters</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select></td> I'm trying to "progressively enhance" one of my surveys using javascript. Basically, I have rating scales that make use of radio buttons as each point on the scale. Each radio button occupies its own cell in a table. I wrote some functions that will highlight cells on mouseover in a color corresponding to its position on the scale (e.g. the lowest point is red, the midpoint is yellow, the highest point is green). When a radio button is clicked, the background of the button's cell and preceding cells in the same row will be colored accordingly. The functions are working well in FireFox and Chrome (I just have to add a few lines using the addEvent function to make it compatible with IE). The effect looks a lot nicer when I add a function that makes the visibility of the radio buttons hidden. However, I want to make sure that there is a fallback option in case the functions that color the cells don't work for whatever reason. I would not want the radio buttons hidden in this case. Is there a method whereby I can call the "hideRadiobuttons" function only if the other functions are successfully executed? Code: <html> <head> <title>TESTING</title> <script type="text/javascript"> <!-- document.write("<input type='submit' value='submit' onclick='func()'>"); function func() { document.write("<input type='submit' value='New Button' onclick='func()'>"); window.alert("THIS"); } --> </script> </head> <body> <!--input type="button" value="Read" onclick="ReadFiles()"--> </body> </html> This is a very basic version of what I am trying to do. I have a dynamic list which is set in a table. When clicked, a function is run to set up a new list.. The reason I explain that, is that I need to keep it dynamic. Now for the problem: When I run this page, I have the button made right away, then when clicked it creates the new button. The new button should also run the function to create the new button again, but when I click it, I only receive "error on page". I don't know if there is a better way to go about this, but as for this route, I am stuck. Any help is greatly appreciated! -Shane My problem is that I am trying to call an function within an SWF. Now, I already know how to setup my SWF and that isn't the problem. The problem is that when I try to call the function using Javascript, I am told that the function doesn't exist. I'll show you the code right here. Code: function AudioPlayerEmbed( e ) { if ( e.success ) { e.ref.LoadAudio( 'http://therevolve.com/upload/userfiles/Music/Alec_Smith1.mp3' ); } } swfobject.embedSWF("player/MP3Player.swf", "flash", "300", "90", "9.0.0", "player/expressInstall.swf", null, null, null, AudioPlayerEmbed ); HOWEVER, when I put some alert before the call, it happens to work. What is going on? Code: function AudioPlayerEmbed( e ) { alert("A"); if ( e.success ) { e.ref.LoadAudio( 'http://therevolve.com/upload/userfiles/Music/Alec_Smith1.mp3' ); } } swfobject.embedSWF("player/MP3Player.swf", "flash", "300", "90", "9.0.0", "player/expressInstall.swf", null, null, null, AudioPlayerEmbed ); Here is a live example. Any help would be appreciated. If you need more information, I can provide it. I'm trying to implement this 'ajax' script, however i'm getting the following error: function expected line 25. And I'm not the only person who is getting this error message :S How can the code be altered so it will work? Also the script isn't executed when I change onclick in onload :S How come and how can I change it so that it will be executed on launch? http://chriscook.me/web-development/...icking-a-link/ Hello. Started my massive JavaScript career just yesterday and the forums I frequent still lack a proper BB-code hide-tag, so I figured I'd try make it in JavaScript, since HTML is allowed on there. This is what I did: Code: <script type="text/javascript"> function show() { document.getElementById('silHideTextTag').innerHTML='Hidden text!!'; document.getElementById('silHideTextBtn').value='Hide'; document.getElementById('silHideTextBtn').onclick='hide()'; } function hide() { document.getElementById('silHideTextTag').innerHTML=' '; document.getElementById('silHideTextBtn').value='Show'; document.getElementById('silHideTextBtn').onclick='show()'; } </script> <input type='button' id='silHideTextBtn' onclick='show()' value='Show'/> <div id='silHideTextTag'> </div> The button labelled "Show" appears fine, when I click it it becomes "Hide" and the text "Hidden text!!" is shown. However, when I click the button again, nothing happens at all. I don't quite understand where the problem is. Thanks in advance for any clues. Best regards, Zyl Hello, if in a webpage is included a javascript file (for example code.js) can I from my browser call a function contained in code.js and will it works correctly? I'm not meaning that the function is called in the page with or without a link to click, but it is only in code.js! Thank you! I am relatively new to JavaScript so am still learning. I have a page I would like to call a function when it loads but not sure how to do this. The function is http://tickettransaction.com/?bid=20...ults&venid=101 and should function similar to this page when loads http://paviliondallas.com/ I could get that with html but not sure how to auto load to render ths list from the provided plugin. Another example is http://www.justbuytickets.com/Venues...FcY32godDU-hzw Any help would be appreciated. Thanks in advance. <frameset rows="30%,70%> <frame src="page1.html" name="name1" frameborder="0"></frame> <frame src="page2.html" name="name2" frameborder="0"></frame> </frameset> in above code I used page1.html & page2.html as frame. Both include same javascript file having two function name fun1() & fun2(). as both are separate frame both have there own copy function page1.html fun1() fun2() page2.html fun1() fun2() I call fun2() from page2.html and inside that function I want to call page1.html's fun1(). fun1() in page1.html and fun1() in page2.html both return different result because of there global variables. Is there any way to call fun1()-page1.html from the fun2()-page2.html? I am trying to make an onblur that calls a function and passes it some text, for example: onblur = "function("Hello")" however this wont work as it is not even calling the function. I have tried all the different encapsulation tags I can think of but still no luck is there any way of doing it or can I assign the text to a variable and call the function in the onblur? Thanks.:confused: Hi, The Problem I get a error message only in IE when ever I try to call a function from an external file. I am using jQuery if that makes any difference and various plugins. Quote: Error: The value of the property '<function name>' is null or undefined, not a Function object. All the call work fine in FF, chrome, safari etc but for some reason I just can't get it to work with IE. This is getting annoying now, i have no idea what is causing it. here is an example: admin.js Code: function create_cleditor_admin_form(textarea_object) { $(textarea_object).cleditor({ height: 120, controls: // controls to add to the toolbar "bold italic underline | color highlight removeformat | bullets numbering | alignleft center alignright justify | undo redo | ", useCSS: false }); } calling code Code: $(document).ready(function() { try { create_cleditor_admin_form('textarea'); } catch(e) { alert("Error: "+e.message); } }); I have tried searching for this error on google and came up empty handed, surely it just something very stupid. Thanks in advance |