JavaScript - Global Number Variable Switching To Nan When Entered Into A Function
Heres a link to the code in question http://www.scccs.ca/~W0049698/JavaTe...erlocktxt.htm#
when the leftPos variable is used in the moveSlide() it somehow turns into Nan. Cant figure out why and have been racking my brain over this for a long time now.. Any help would be greatly appreciated the problem is at the end of the code(scroll to the bottom) ======================================================= Code: window.onload = makeMenus; var currentSlide = null; var timeID = null; function makeMenus(){ var slideMenus = new Array(); var allElems = document.getElementsByTagName("*"); for(var i=0 ; i < allElems.length ; i++){ if(allElems[i].className == "slideMenu") slideMenus.push(allElems[i]) } for(var i=0 ; i < slideMenus.length ; i++){ // alert(slideMenus.length) slideMenus[i].onclick = showSlide; slideMenus[i].getElementsByTagName("ul")[0].style.left = "0px"; } document.getElementById("head").onClick = closeSlide; document.getElementById("main").onClick = closeSlide; } function showSlide(){ slideList = this.getElementsByTagName("ul")[0]; if(currentSlide && currentSlide.id == slideList.id) {closeSlide()} else{ closeSlide(); currentSlide = slideList; currentSlide.style.display = "block"; timeID = setInterval("moveSlide()", 1); } } function closeSlide(){ if(currentSlide){ clearInterval(timeID); currentSlide.style.left="0px"; currentSlide.style.display="none"; currenSlide = null; } } Code: Similar TutorialsI am trying to figure out how to assign a value to a global variable within a function and can't seem to figure it out. Here's my thought, Code: <script type="text/javascript"> var global1=""; var global2=""; function assign(vari,strng){ vari = strng; } </script>... <input name="box1" onblur="assign('global1',this.value)"/> <input name="box2" onblur="assign('global2',this.value)"/> ... The purpose behind this is creating a form that will work with an existing database that would normally have a text area with lots of information. I am trying to turn it into a checklist that I can run from a mobile device. The global variables woudl be used to fill in a hidden text area that would then be passed on to the database upon submission. I am trying to keep the code as compact as possible. Any ideas? hello im trying to change a variable set outside of a function and calling the function with an onchange... i'm having problems getting the variable to change Code: <script type="text/javascript"> var price = '<?php echo $price; ?>'; function addtwo() { if(document.add.size.value == "2xl") { price = price + 2; } } </script> Hi, Is is possible to access a global variable for use inside a function? Thanks for help in advance Mike Hello I'm using simpleCart() javascript shopping machine for my page. The script accepts values in a specific syntax: Code: onclick="simpleCart.add('name=Some name','price=23.4','quantity=1');" But because the price of the product is not always the same but comes up after previously made calculations, i want to parse the values in simpleCart() through another function. I have made the following one which gets the price from a textbox (resultAlmires) of a form (Almires), then converts it to american format (. instead of ,) makes it have one decimal only and finally parse it to simpleCart() with the use of a variable. However it doesn't seem to work: Code: function addAlmiri() { var timi = document.Almires.resultAlmires.value; timi = timi.replace(/\,/,"."); timi = timi.toFixed(1); simpleCart.add( 'name = Some name' , 'price = timi' , 'quantity = 1' ); } Any help? Hey friends, I'm writing a program but I'm having issues. I need to write a program that asks for 3 different numbers (prompt boxes) and determine which number entered was the highest and the 2nd highest. I know what to do for the input and output but I don't know what to do during the processing.
hello I want ask how can i declare global variable in html file , and use it in java script file . - with same value- thanks I am working with the google blogger API, and I am having an issue updating my global variable Response. I thought I understood how global variables worked, so I don't know if there is something different about the blogger API or if I'm making a dumb mistake. Code: <SCRIPT TYPE="text/javascript" src="http://www.google.com/jsapi"></ script> <script> google.load("gdata","1.x", {packages: ["blogger"]}); google.setOnLoadCallback(getMyBlogFeed); blogID = "1601946089552390859"; var feedUri = "http://www.blogger.com/feeds/"+blogID+"/posts/full?alt=json"; var Response = ""; function getMyBlogFeed(){ var myBlog = new google.gdata.blogger.BloggerService('GoogleInc-jsguide-1.0'); myBlog.getBlogPostFeed(feedUri, handleBlogFeed, handleError); } function handleBlogFeed(myResultsFeedRoot) { Response = myResultsFeedRoot.feed.entry[0].content.$t; } function handleError(e) { alert("There was an error in getBlogPostFeed"); alert(e.caue ? e.cause.statusText : e.message); } alert(Response); </SCRIPT> Here's what I think SHOULD happen: Response is initialized as a global variable with a value of "" setOnLoadCallback calls getMyBlogFeed which creates a blog object, then calls getBlogPostFeed which calls handleBlogFeed. handleBlogFeed stores a new string to global variable Response an alert pops up with the value of Response (as given by handleBlogFeed) What actually happens is that the alert pops up with the original value of Response. I know that I can issue the alert inside handleBlogFeed, but that isn't the issue. My issue is that I'd like to use Response in other functions, but it isn't being updated as a global variable. What am I doing wrong that Response isn't updating? On a related note, is there a way to return a variable from my handleBlogFeed function? How would I do that? -- I can't seem to figure it out. Thanks! P.S. I recognize that the best place to ask this is the blogger developer group. I've already posted this there, and no one has responded yet. Hi, Here's a sample form: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Sample form</title> <script type="text/javascript"> function displayResult() { alert(document.myForm.myInput.value); } function getFocus() { if (document.myForm.myInput.value == document.myForm.myInput.defaultValue) { document.myForm.myInput.value = ""; } } function loseFocus() { if (document.myForm.myInput.value == "") { document.myForm.myInput.value = document.myForm.myInput.defaultValue; } } </script> </head> <body> <form name="myForm" method="get" onsubmit="return false;" action=""> <input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"><br> <input type="button" onclick="displayResult();" value="Display input value"> </form> </body> </html> It works with no problem, but the following doesn't: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Sample form</title> <script type="text/javascript"> var x = document.myForm.myInput; function displayResult() { alert(x.value); } function getFocus() { if (x.value == x.defaultValue) { x.value = ""; } } function loseFocus() { if (x.value == "") { x.value = x.defaultValue; } } </script> </head> <body> <form name="myForm" method="get" onsubmit="return false;" action=""> <input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"><br> <input type="button" onclick="displayResult();" value="Display input value"> </form> </body> </html> What's wrong with it and how can I define a global variable to be used by all the functions? Many thanks in advance! Mike Hey all! Got a question I can't seem to find an answer to. I have a little JS app that is a glorified calculator which I posted the code for below. My code uses the document object to replace the html in the "content" <div> and works great. However, I want to add an inline style in order to change the background of the input (readonly field with an id of "coutput") based on either of the global variables named "MJPD" or "IJPD", (depending on the switch case selected in the user prompt at the beginning of the script.) Simplified....if the value of MJPD is less than 4.6, I want the "coutput" field's background to be red, else be green. The same goes for IJPD, except the threshold for red will be <3.83. Code and what I have tried is below. After reading the code, look below it to see what I have tried and maybe tell me what I'm doing wrong! =) Any help is greatly appreciated.......I have spent a week searching for this little answer and I can't seem to find it! Code: <script language="JavaScript"> var MJPD = 1; var IJPD = 1; function sayhello(){ // *** live test for inline JS code placement alert("IT WORKS!!! Now change me =)"); } ////////////////////////////////////////////////////// function changeScreenSize(w,h) { window.resizeTo( w,h ) } /////////////////////////////////////////////////// function iJPDCalc(form) //calculate IJPD value { var ij = parseFloat(form.IJobs.value, 10); var it = parseFloat(form.ITime.value, 10); var IJPD = 0; IJPD = (ij / it) * 8.0; form.I_JPD.value = IJPD; } ///////////////////////////////////////////////////// function mJPDCalc(form) //calculate MJPD value { var mj = parseFloat(form.MJobs.value, 10); var mt = parseFloat(form.MTime.value, 10); var MJPD = 0; MJPD = (mj / mt) * 8.0; form.M_JPD.value = MJPD; } ///////////////////////////////////////////////////// function ijpdcolor() //set bg color of coutput based on IJPD's value { if (IJPD >= 3.83) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function mjpdcolor() //set bg color of coutput based on MJPD's value { if (MJPD >= 4.6) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function startVZT3(){ var n=0; n=prompt("What would you like to do? 1: Calculate IJPD 2: Calculate MJPD 3: Exit", "Enter a value from 1-3") switch(n) { case(n="1"): document.getElementById("content").innerHTML='<FORM><h2>Combined IJPD Calculator</h2><p>Install components completed today:</p><INPUT NAME="IJobs" VALUE="3.84" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="ITime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your IJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=iJPDCalc(this.form)><p>Your current combined IJPD for today is:</p> <INPUT NAME="I_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="2"): document.getElementById("content").innerHTML='<FORM><h2>Combined MJPD Calculator</h2><p>Trouble components completed today:</p><INPUT NAME="MJobs" VALUE="4.6" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="MTime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your MJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=mJPDCalc(this.form); mjpdcolor();><p>Your current combined MJPD for today is:</p> <INPUT NAME="M_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="3"): alert('This page will now close...'); window.close(); break default: document.getElementById("content").innerHTML='<h1 style="padding-top: 40px; color: red;">You need to enter a value! Please try again...</h1>'; break } } /////////////////////////////////////////////////////// </script> </head> <body onload="changeScreenSize(825,775)"> <div id="wrapper"> <div id="sub_wrapper"> <br /> <br /> <input type="button" class="button" onclick="startVZT3()" value="Start VZT3 Web!" /> <br /><br /> <div id="content"> <h3 style="padding-top:60px;">VZT3</h3> </div> </div> <script type="text/javascript"> <!-- trying script to ensure function and dynamic update of this value - doesnt work 2/3/2010 --> document.write(mjpdcolor()); </script> </div> </body> OK, so on the last line of each case statement where it injects html code into the content div, in this code style=" background: ** ** " and in between the ** ** marks, I have added such things as <script type="text/javascript">document.write(mjpdcolor())</script> (or ijpdcolor, depending on which case I am working with). Theoretically, this should pull the value of MJPD (or IJPD), evaluate it for the if statement, then return the value of red or green and set the value of the background dynamically - but of course it doesnt. I have also tried different inline styles and even adding the css id and trying to link it to the mjpdcolor() function, but all to no avail. Can someone help me please?? Thanks everyone, your awesome! I've read through the past threads and did not find anything that quite matched my problem, which surprises me because I thought it would be fairly common. Anyway, I have a script where I define an array and populate the array. In the same script is a function that tries to scan the table looking for a match with the value in a global primitive. In the HTML, a button click invokes the function. But while the function can correctly access the global primitive, it simply stops running when it encounters the reference to the global array. Here's a shortened, simplified snippet of the code: [code] <script type="text/javascript"> var len = 2; var course_code = new Array(); course_code[0] = "A010"; course_code[1] = "A500"; function runcodes() { alert('In runcodes'); alert('len = '+len); alert('course_code.length = '+course_code.length); for (i = 0 ; i < course_code.length ; i++) {alert(course_code '+i+' = '+course_code[i]);} } </script> <body> <button type="button" name="runc" id="runc" onclick="runcodes()"; > Click to display course codes table. </button> </body> [ICODE] When I bring this up in a browser and click the button, I get the following alerts: In runcodes len = 2 and then the script simply stops. So it stops on the first reference to the array. Clearly I am getting to function, and the function is able to handle the global primitive 'len', but it stops on encountering the global array. I've tried a lot of variations on the the theme, but nothing gets past this restriction. How do I access elements in a global array from inside a function? Forgive but I'm quite a beginner at JS . . . Anyway, on my website I've got a form, and then a script that validates the form. The script for validation is inside a function. The problem is that I have another script outside of the function that generates random numbers to make sure there's not a spambot submitting the form. I set a variable called 'answer' as the correct answer, but for some reason, the variable won't be read when I put it inside the original function to make sure the user got it right. How should I go about doing this? Thanks, Raybob Code: <!-- THIS SCRIPT ENSURES FIELDS ARE FILLED OUT CORRECTLY --> <script type="text/javascript"> var x1 = Math.floor(Math.random()*11); var x2 = Math.floor(Math.random()*11); var ans = x1+x2; </script> <script type="text/javascript"> <!-- function validate_form ( ) { var valid = true; var at = document.newaccount.email.value.indexOf ("@"); var dot = document.newaccount.email.value.lastIndexOf ("."); if ( document.newaccount.name.value == "" ) { document.getElementById('noname').style.display = 'inline'; valid = false; } if ( at < 2 || dot < at+2 || dot+2 >= document.newaccount.email.value.length ) { document.getElementById('wrongemail').style.display = 'inline'; valid = false; } if ( document.newaccount.password.value == "" ) { document.getElementById('nopassword').style.display = 'inline'; valid = false; } if ( ( document.newaccount.password2.value == "" ) && ( document.newaccount.password.value !== "" ) ) { document.getElementById('nopassword2').style.display = 'inline'; valid = false; } if ( ( document.newaccount.password.value !== document.newaccount.password2.value ) && ( document.newaccount.password.value !== "" ) && ( document.newaccount.password2.value !== "" ) ) { document.getElementById('nomatch').style.display = 'inline'; valid = false; } if ( ( document.newaccount.password.value.length < 8 ) && ( document.newaccount.password.value !== "" ) ) { document.getElementById('passwordlength').style.display = 'inline'; valid = false; } if ( ( document.newaccount.agree[0].checked == false ) && ( document.newaccount.agree[1].checked == false ) ) { document.getElementById('noagree1').style.display = 'inline'; valid = false; } if ( ( document.newaccount.agree[0].checked == false ) && ( document.newaccount.agree[1].checked == true ) ) { alert ( "Sorry, but you must agree to the terms and conditions before creating an account." ); valid = false; window.location = "/terms.html" } if ( document.newaccount.spamcheck.value == "" ) { document.getElementById('nomath1').style.display = 'inline'; valid = false; } if ( ( document.newaccount.spamcheck.value !== ans ) && ( document.newaccount.spamcheck.value !== "" ) ) { document.getElementById('nomath2').style.display = 'inline'; valid = false; } if ( (!document.newaccount.store.checked) && (!document.newaccount.share1.checked) && (!document.newaccount.share2.checked) ) { document.getElementById('noinfo').style.display = 'inline'; valid = false; } return valid; } //--> </script> <!-- END OF SCRIPT --> Code: <form name="newaccount" onsubmit="return validate_form ( );" action="/submitted.html" method="get" > <center> <table style="text-align:center;" ><tr><td> What's <script type="text/javascript"> document.write (x1 + " " + "+" + " " + x2); </script> ? <input type="text" size="5" name="spamcheck" /></td></tr></table> <br /> <br /><br /> <input type="submit" name="send" value="Submit" /> </center> </form> 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! Hi there I'm nearly completed on a game, and want to bring in "Lives", basically, rather than the game ending, running "function EndGame ()" I want to allow the player to carry on with "Lives", 3 in fact. Basically, when the player presses a wrong tile, the game needs to carry on, until the last life, life 3 is lost, then "function EndGame ()" runs.. I believe a Global Variable needs to be used? If any help could be given that would be great, also if it could be shown in JSFiddle, that would be great! Many thanks Reply With Quote 12-18-2014, 03:56 PM #2 Dormilich View Profile View Forum Posts Senior Coder Join Date Jan 2010 Location Behind the Wall Posts 3,532 Thanks 13 Thanked 372 Times in 368 Posts Originally Posted by LONDONLAD I believe a Global Variable needs to be used? nope. you can use a global, but you should not. better use the variable/container that you store the player or game status in. I don't know how I should do ? Quote: <html> <head> <script type="text/javascript"> function add(a,b){ y=a+b return y } var aaa = add(one,two) //one needs to get somehow get the value of yil, in this case 10 var one = function reas(){i=10;if(i<10){yil = 15}; else{yil = 10; yil = one;}; var two = 20; document.write(y) </script> </head> </html> also why doesn't this work? Quote: <html> <head> <script type="text/javascript"> function adder(a,b){ var k=a+b; return k } var hes=adder(5,kol); kol=40; alert(hes); </script> </head> </html> you cannot have variables in callback functions? Thank you in advance if someone can help. I have been banging my head against the wall for hours now. Here is the code: Code: for (var i = 0; i < BS_crm['activityTypes'].length; i++) { var clickFunc = function(){ activityList.showForm( -1, {blockType:[""+BS_crm['activityTypes'][i]['id'], "0"]} ); }; var type = { value: BS_crm['activityTypes'][i]['id'], label: "Add New "+BS_crm['activityTypes'][i]['label'], css: BS_crm['activityTypes'][i]['css']+"_16", onClick: clickFunc }; previewLinks.items.push( type ); } Now, basically what I am doing here is running through one array to create an array of objects, that will be used to create links that will use whatever onClick function I pass it. The problem is that on the second line I need the BS_crm['activityTypes'][i]['id'] to be a value, not a reference. If that line was simply changed to: Code: var clickFunc = function(){ activityList.showForm( -1, {blockType:["3", "0"]} ); }; then everything would work as I need. How can I make this happen? I would really appreciate any help. Thank you again in advance. I am working on an HTML project that displays a field with a number in the field by each day. What it does is start at 0 on day one. Each day it adds a 1 to the field. Day 2, the field would say 1, then day 3 would say 2, and so on. I am not sure how to approach this. This is also displayed in an HTML format. I want to to be automatic and change as the date changes. I will also need a way to reset it back to zero if possible.
Hi I'm trying to get a variable named 'html' from one function and use it in another. My JavaScript knowledge is limited, so will be grateful for any help Please see code below Code: function createMarker(point, name, label, address, type) { var marker = new LabeledMarker(point, {icon: customIcons[type], labelText: label, labelOffset: new GSize(-6, -10)}); markerGroups[type].push(marker); GEvent.addListener(marker, 'click', function() {GEvent.trigger(map,"click",null,point,point); var html = '<div>LatLng:' + name + '</div><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().maximize()">more info.. </a>'; marker.openMaxContentTabsHtml(html); }); return marker; } // need to get html variable from the above function into this one below GEvent.addListener(map, 'click', function(ov, latlng, ovll) { if (latlng) { var regular = '<div id="sum">LatLng:' + latlng + '</div><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().maximize()">more info.. </a>'; var summary = '<div id="sum">Address of' + latlng + '</div><a href="javascript:void(0)" onclick="javascript:map.getInfoWindow().restore()">less info.. </a>'; var panoDiv = document.createElement('div'); panoDiv.width = "400px"; // can be anything, will be auto resized panoDiv.height = "200px"; var tabs = [new MaxContentTab('address', '<div id="address"></div>'), new MaxContentTab('streetview', panoDiv)]; map.openMaxContentTabsHtml(latlng, regular, summary, tabs, { maxTitle: "More Information", selectedTab: 'address',// or use index 1, style: { tabOff: { backgroundColor: '#CCCCFF' } },maximized: document.getElementById('maximized').checked }); } }); Example: Function First() { Var = x1 <--- Use this variable } Function Second() { Var = x2 Var = x1 + x2 } I know this is not the way in the example...but just making sure you know what im talking about. Hi there, Sorry that the title of this is not very descriptive but I really don't know how to describe what it is i am after. I have a variable that contains an image source. (well I hope it does) Code: var imagebackground = (this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).src; Now I need that variable to spit out the image source into where it says background, but wrapped in a url( ) Code: $jQ(document).ready(function(){ $jQ(".btn-cart").click(function(){ $jQ('#floater').animate_from_to('.block-cart', { pixels_per_second: 200, initial_css: { background: (THIS IS WHERE I WANT IT) } }); $jQ(this).attr('id', ''); $jQ(this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).attr('id', ''); }); }); So basically if the variable was to equal - http://www.google.co.uk/image.jpg - it would function like: Code: $jQ(document).ready(function(){ $jQ(".btn-cart").click(function(){ $jQ('#floater').animate_from_to('.block-cart', { pixels_per_second: 200, initial_css: { background: url(http://www.google.co.uk/image.jpg) } }); $jQ(this).attr('id', ''); $jQ(this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).attr('id', ''); }); }); I hope I have provided enough information for someone to assist me with this, but if i havent then please tell me and i will try and explain some more. Cheers, Chris |