JavaScript - General Function Help
Hi,
I need help creating a function. It want it to: run when the page loads and every x seconds after. On loading I need it to connect to a db(preferably w ajax) and store results as variables I can reuse in other functions. And finally, after some math equations I can do, print the results on the page. I've been toying with this and I've realized its not as easy as I thought. Think I'm having problems with variable scope. Php is my main scripting language, of which I am fluent and have a working version of this. But I want it to run on the client side and relieve my server. Sorry if this is vague or incorrectly formatted, I'm on a phone browser. A guide or detailed demonstrations would be great, however pointing me in the right direction would me most apreciated. Similar TutorialsHi, To put it bluntly I am a newbie to Javascript. I manage my own site using skills I have developed through learning code and need some help with debugging. My website is www.simplysafes.co.uk, in my IE it tells me I have an error with line 106 and char 2. Can anyone help me with this?? I would really appreciate it. Thanks in advance. James Hello; I'll begin like so many others before me, and apologize now if this post is in the wrong place, but since I don't exactly know what type of code I need, I'm not sure where to post this query. Let me preface this request by stating the obvious; I have almost no knowledge of coding. I've been watching tutorials for help with building a site for my small service-type business. I need coding that will allow my visitors to input their zip code to see if they reside in my service area. After they enter the zip and click the submit button, a page should pop up with one of two messages when they either are or are not in my service area. (I would undoubtedly need to list [somewhere in the coding] all the zip codes that are within my service area, and any zip codes not listed would bring up a message that the visitor is outside my service area.) I hope this makes sense, and someone can point me in the right direction. Thank you, in advance to any and all who respond, and keep in mind that you may have to dumb-down your responses for me to be able to understand. I have a general javascript question. It may apply in this forum but maybe in the asp forum. I have a java applet on a site that I am building. If someone visiting the site doesn't have their javascript turned on, and chooses not to, is there some line of code that I can use that will detect that and replace the applet for an image I create? The site is developed in asp, but being that it is a javascript question, I thought it may apply here. Gary I create a cookie on my homepage that tracks a number, the next time they view, js calculates another number and subtracts the saved number. Is the cookie value created accessible from a page other than the home page? i.E. I want to create a popup window that shows the calculation but i can seem to pass the variable generated from my external js script to the internal script/page. Am i able to call the getCookie class i created from the internal script even if the class is held in the external script or is it only accessible from the page that created the cookie? If its a dumb question, sorry im relatively new. I've only just stated to teaching myself the general basics of web development, and I've hit a problem which I haven't been able to fix, even after some extensive research I haven't found a solution. The problem is not in the HTML I'm quite sure, hence why I deemed this to be the best place to post this. I'm sorry for wasting your time on something stupid like this, but I'm completely lost! Extra: I really couldn't think of a title that could describe this 'problem', my bad. Description: When clicking the calculate button nothing happens, but when I changed the code inthere to something easy (just print a line in a HTML paragraph) it worked. So by that I was able to deduce the problem lies somewhere in the Javascript. Code: <!DOCTYPE html> <html> <body> <div> <form> <fieldset> <h1>Quadratic equation</h1> a:<input type="text" id="a" name="a"><br><br> b:<input type="text" id="b" name="b"><br><br> c:<input type="text" id="c" name="c"><br><br> <button type="button" onclick="vkv()">Calculate</button> </fieldset><br> <fieldset> <p id="output">Answer appears here</p> </fieldset> </form> </div> <script> function vkv() { var a = document.getElementById(a); var b = document.getElementById(b); var c = document.getElementById(c); var D = pow(b,2) - 4 * a * c; if (D >= 0){ var x1 = (-b + sqrt(D)) / (2 * a); var x2 = (-b - sqrt(D)) / (2 * a); if (x1 == x2) { document.getElementById("output").innerHTML = "Value for x is:" + x1 + "."; } else { document.getElementById("output").innerHTML = "Values for x a " + x1 + " en " + x2 + "."; } } else { document.getElementById("output").innerHTML = "Discriminant is negative, " + D + "."; } } </script> </body> </html> Reply With Quote 02-03-2015, 10:31 PM #2 jmrker View Profile View Forum Posts Senior Coder Join Date Aug 2006 Location FL Posts 3,175 Thanks 39 Thanked 510 Times in 504 Posts Welcome to the forum... NOTE: I have not tested the logic of your code to see if it give the right answers, but this should get you started by at least seeing some results displayed. Primary problem was not using Math. before the math commands like pow and sqrt. Also, need quotes around id values in the document.getElementById statements And those statements require a value associated with the element Plus, it returns a string, hence the need for a Number() function or some other string to conversion. It is always a good idea to check the error console on most browsers to get an idea of the simple problems. That's where I found most of your errors. Code: <!DOCTYPE html> <html> <body> <div> <form> <fieldset> <h1>Quadratic equation</h1> a:<input type="text" id="a"><br><br> b:<input type="text" id="b"><br><br> c:<input type="text" id="c"><br><br> <button type="button" onclick="vkv()">Calculate</button> </fieldset><br> <fieldset> <p id="output">Answer appears here</p> </fieldset> </form> </div> <script> function vkv() { var a = Number(document.getElementById('a').value); var b = Number(document.getElementById('b').value); var c = Number(document.getElementById('c').value); var D = Math.pow(b,2) - 4 * a * c; if (D >= 0){ var x1 = (-b + Math.sqrt(D)) / (2 * a); var x2 = (-b - Math.sqrt(D)) / (2 * a); if (x1 == x2) { document.getElementById("output").innerHTML = "Value for x is:" + x1 + "."; } else { document.getElementById("output").innerHTML = "Values for x a " + x1 + " en " + x2 + "."; } } else { document.getElementById("output").innerHTML = "Discriminant is negative, " + D + "."; } } </script> </body> </html> Good Luck! hi, I would like your help on the following matter. I have a JavaScript file currently reading from another site xml file in (utf-8) and I would like to store those data in my database which is in SQL_Latin1_General_CP1_CI_AS. Is there any function in JavaScript that can encode (convert) text from utf-8 to SQL_Latin1_General_CP1_CI_AS or any other way to do that? Hello, I'm new to this forum. I want to improve my ability to write JavaScript and am looking for a friendly place to find some constructive criticism and suggestions on my code. This script does not have any practical use (that I can think of); it calculates prime numbers. It is just an exercise. I am looking for suggestions on all aspects from the CSS/aesthetics to the HTML and of course the JavaScript. I posted the script here. One definite thing that bugs me is the cursor is not in the text field when the page loads. Also it would be better if the user had the option of hitting the return key in addition to the submit button. Suggestions appreciated. Code: <!DOCTYPE html> <html lang="en"> <head> <title>Prime Number Calculator</title> <style type="text/css"> form{ width: 200px; border: solid 3px blue; border-style: double; padding:5px; text-align:center; background-color:#eee; } #title{ text-align:center; border: solid 1px blue; background-color:#fff; margin:5px; padding:0px; } </style> <script src="jquery.js" type="text/javascript"></script> <script type="text/javascript"> var candidates = new Array(); function calculatePrimes(form){ var max = form.input.value; //Check to make sure input is a number if(isNaN(max)){ alert("Dude, you must enter a number!"); } for(i=2; i<=max; i++){candidates[i]=i;} var i=2; for(i=2; i<Math.sqrt(max); i++){ if (candidates[i]!=0){ var j=i*i; while(j<max){ candidates[j] = 0; j=j+i; } } } //Pull the primes out of the candidates i=2; var primesOut = ""; for(i=2; i<max; i++){ if(candidates[i]!= 0){ primesOut = primesOut + ((i>2)?", " : "" ) + candidates[i]; } } form.output.value = primesOut; } </script> <head> <body> <form> <h2 id="title">Prime-Number Calculator</h1> Check up to:<input type="text" name="input" size="5" value="100" \> <br /> <textarea rows="5" cols="20" name="output"></textarea> <input name="calc" value="Find!" type=button onClick="calculatePrimes(this.form)"> </form> </body> </html> Hi, as the title states, I'm trying to learn some basic javascript, more particularly, jQuery. I HATE having to "allow" active content to run on my IE browser. Is there a way to allow active content permanantly? Instead of having to click allow each time I refresh or reload my test pages? Also, IE keeps freezing or crashing when I run pages with scripts on them. Is this just my browser? or something to do with the active content permissions? Trying to google my questions, but no luck yet. Hi could someone please help?... I am a total beginner to javascript... but does anyone know of a code, including links to an image folder, for displaying 6 fullscreen images in random order without repeat for a given user? I've seen specific examples using shuffle on the site, but could anyone write a general code for any given images? Many thanks in advance Hi, I am facing a problem in passing replace() function as an argument in user defined java function, can any one help me how to resolve it? intention is to pass a file path to my user defined function, but before passing the path i want to replace the character '\' to '\\' I am posting my javascript function he <a href="#" onclick="OpenDocPreview('<%# Eval("PATH")%>'.replace(/\\/g,"\\\\"), '<%# Eval("Filename")%>')"><%# Eval("DocTitle") %></a> function OpenDocPreview(url, docname) { alert('message from search base : ' + url + ' ' + docname); } thank you, I was working on a tutorial for some ajax uploading stuff and I ran across a new function syntax I don't recognize. I am not a Javascript pro, but I am not a newbie either. here is the code I am working on: Code: function handleFileSelect(e){ var files = e.target.files; var output = []; for(var i=0,f;f=files[i];i++){ if(f.type.match('image.*')){ var reader = new FileReader(); reader.onload = (function(theFile){ return function(e){ var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" src="',e.target.result,'" title="',theFile.nbame,'" />'].join(''); document.getElementById('list').insertBefore(span,null); }; })(f); reader.readAsDataURL(f); } } document.getElementById('list').innerHTML = '<ul>'+output.join('')+'</ul>'; } document.getElementById('files').addEventListener('change',handleFileSelect,false); To be a little more clear, the code in question is that is the very middle. The syntax I don't understand is: Code: class.event = (function(arguments){ //stuff you put in a function... })(more Arguments?); I tried to customize a simple one to learn for myself and I wrote this: Code: var a = 'A'; var b = 'B'; test = (function(t){ alert(t); alert(b); })(b); test(a); The browser would alert 'B' and that's it. The console would tell me that 'test is not a function.' OK, so I am confused. The topmost code works. What I am wondering is what the syntax is called for creating a function (or event listener?) that way, and how it works. Although if I new what it was called I could just google how it works. Hi! I'm trying to toggle a class and one works and the other does not and I don't know why. I'm just getting my feet wet with jquery and javascript and I figured this was a pretty easy task to take on! Maybe. Link to the page: Franklin Township Soccer Club - Change Field Status My sad, sorry attempt =| Code: $( "li.open" ).click(function() { $( this ).toggleClass( "closed" ); }); $( "li.closed" ).click(function() { $( this ).toggleClass( "open" ); }); The first function works with open, so I figured I'd just use opposite on closed! Ha! I don't think so! In the end within those function there is an element in a form on that page it's hidden. I'd like to change the value from a 0 to 1 for vice versa. That' will be my next step. If you could give me a little nudge in the right direction I'd appreciate it! But first understanding why one works and the other does not, that is the primary mission! I do appreciate any help given! Dave <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> Hi All, I'm trying to convert an anonymous function to a real function (nesting is getting out of hand), however the msg object becomes undefined after conversion. Here is the converted anonymous function which fails: https://gist.github.com/2587613 and here is the original anonymous function which works: https://gist.github.com/2587667 Any help would be greatly appriciated I found this script, and it works great: Code: <script type="text/javascript"> function disable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","true"); } } </script> I tried to make the inverse by simply reversing the setAttribute() like so: Code: <script type="text/javascript"> function enable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","false"); } } </script> But that didn't do it. Can someone show me why, and how to fix it? Here's the sample form which I'm trying to test it on: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> disable<br/> <input type="radio" name="test" onclick="enable('D1')" /> enable<br/> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /><br/> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /><br/> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /><br/> </fieldset> </form> Edit: The ultimate goal which I'm working toward now (step by step =) is to have a form more like: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /> </fieldset> <input type="radio" name="test" onclick="disable('D2')" /> <fieldset id="D2"> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /> </fieldset> <input type="radio" name="test" onclick="disable('D3')" /> <fieldset id="D3"> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /> </fieldset> </form> And have the fieldsets enable and disable according the selection of the radio buttons. Also, the fieldsets (and their ID's) will be dynamically generated via PHP Thanks-a-bunch, ~ Mo 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> 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? I made a mouseover event of a caption on a picture, when I hover the opacity of the background color of the hover and the text goes down. What I want is that when I hover over the image which the caption is floating on, the onmouseover event gets activite. For an imaginary example: Code: function unhighlight(x) { x.style.backgroundColor="transparent" } Function ActivationFuction() { activate.function="unhighlight" } thanks How can I call a PHP Function inside a Javascript Function? This is what I have so far, but I don't think I'm doing it the right way. Any suggestions? PHP Code: <?php function phpQuery(){ $query = mysql_query("INSERT INTO mytable VALUES('','name','email')"); } ?> <script type="text/javascript"> function delayQueries() { timeoutID = window.setTimeout(doQueries, 2000); } function doQueries() { var runQuery = "<?php phpQuery(); ?>"; } </script> 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 |