JavaScript - Trouble With A Pickstring Function
Hi I'm having trouble with the pickString function bellow the getRandomNumber function. When working it should be invoked using the variable "termString" (bellow) as the argument. I hope someone can help as i can't move on without this section working. Thanks
<SCRIPT language="JavaScript"> //TO DO: PASTE THE getRandomNumber() FUNCTION YOU WROTE FOR TASK 1 HERE function getRandomNumber(aNumber) { var rand = Math.floor(Math.random() * aNumber + 1); return (rand); } //Task 2 (iii)(a) /* Picks a random substring from a string separated by delimiter characters. The function takes two string arguments: a String separated into substrings by a delimiter aDelimiter, a string of one character returns a string */ function pickString(aString, aDelimiter) { var aString = new Array(); var stringArray = aString.split(); var stringArray = getRandomNumber(stringArray.length); return stringArray; } var termString = 'hard disk*Term 1#magnetic tape*Term 2#flash drive*Term 3#optical disc*Term 4#ram*Term 5'; //WRITE CODE TO INVOKE THE pickString() FUNCTION HERE //WRITE CODE TO SPLIT THE STRING RETURNED BY pickString() INTO AN ARRAY HERE //WRITE CODE TO DISPLAY THE TERM RETURNED BY pickTerm() AND ITS ASSOCIATED NUMBER HERE </SCRIPT> </HEAD> <BODY> <STRONG>A test of the random number functions <BR></STRONG> <FORM NAME = "randomForm"> <INPUT TYPE = "button" NAME = "randomButton" VALUE ="Display Random Number" ONCLICK = "window.alert(termString);"> </FORM> </BODY> </HTML> Similar TutorialsHi all, Basically I'm having trouble writing a date function to return this data: [CODE] // Get Date d=new Date(); a=d.getUTCFullYear(); b=d.getUTCMonth() + 1; c=d.getUTCDate(); e=d.getUTCHours() - 1; f=d.getUTCMinutes(); [CODE] I need it so I can run setinterval on the date function. I'm quite new to javascript (obviously!) so any help will be much appreciated. Thanks Array.prototype.each = function (fn) { this.map(fn) } This is my each function that works great in every other browser but IE. UGH! What am I doing wrong? the error points to the this in the function. Is it that IE doesn't like map? Has anyone seen this before? I thought my code was correct. Works perfect in FF, chrome and opera. the canvas text doesn't work in opera, but it does render the features so the each function is working. I'll post the code if needed, but it's huge. here's the script running. http://www.pdxbusiness.com/canvas/golf/ I am taking an online class and the instructor is no help whatsoever. Please see where I'm going wrong with this. I'm sure it is something small I'm missing. Thanks. The assignment is: Create a function named emLink() that writes an email address using text strings of the username and server names entered in reverse order as parameter values. The command to call the function would look as follows: emLink("eman","revres"). Call the stringReverse() function with name as the parameter value to reverse the order of characters. Code: <html> <head> <script type="text/javascript"> function emLink(name,server) { var rname="eman"; var rserver="revres"; stringReverse(rname); stringReverse(rserver); var email="eman@revres"; var mailText='<a href="mailto:eman@revres">"eman@revres"</a>'; document.write(mailText); } function stringReverse(textString) { if (!textString) return ''; var revString=''; for (i = textString.length-1; i>=0; i--) revString+=textString.charAt(i) return revString; } </script> </head> <body> <script type="text/javascript"> var rname="reldac"; var rserver="ude.ortsa.uwm"; emLink(rname,rserver); </script> </body> </html> Currently, all it returns it : "eman@revres" I am trying to create a simple auto-calculate function for a webpage. What should be happening: The 'onchange' command should pass the 'price' of the item to the function, the function should then cycle through all the dropdowns (or checkboxes or fields) and calculate the total. What is happening: It is only picking up the last checkbox. It seems that the 'for' loop only remembers the last item in the array. What am I doing wrong? How can I get the code to remember all the items? thanks, Code: <script language="JavaScript" type="text/javascript"> function calculateTotal(price) { var total = 0; var cList = ['sel1','sel2','sel3']; for (i=0;i<2;i++); var select = GetE(cList[i]); total+= price * (select.options[select.selectedIndex].value); GetE("totalShow").innerHTML = total.toFixed(2); } function GetE(id) {return document.getElementById(id); } </script> <html> <head></head><body> <form id="form1" name="form1" method="post" action=""> <select name="sel1" id="sel1" onchange="calculateTotal(100)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> <select name="sel2" id="sel2" onchange="calculateTotal(200)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> <select name="sel3" id="sel3" onchange="calculateTotal(300)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> </form> <br>total <span id="totalShow">0.00</span> </body></html> 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. 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 <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! 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 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 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? 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 Hi, Any one help me In one variable i have some data ex: var data = document.getElementById("imageId").value; I want to pass this data to another function inside another function ex: var button1 = '<img src="images/Remove-button.gif" width="70" height="15" onclick="removeVerifyImageRow(this),saveLibData('+data+')"/>'; while running the application i am getting an error incase if the data is string ex:if data is 'image1' i am getting an error, but with number there is no problem ex: if data is '1122'. this is very urgent to solve this problem plz any one help me 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 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. 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> Hi, I am working on a google map where you can show lines on the map by checking checkboxes. Lines are displayed according to their category attribute in the xml file. The function that picks up the checkbox click is like this: Code: function boxclick(box,category) { if (box.checked) { show(category); } else { hide(category); } Another part of the code assigns that category attribute to arrows, so that when a line of "x" category is displayed, the relevant arrows are displayed along with it, to indicate directionality. I also have a select list which displays the lines by looping through their array and using selectedIndex in a function called handleSelected2. But I can't get the arrows to display along with the lines from the select box. After trying many, many things, I figure that all I need to do is to call the show(category) function from inside the handleSelected2 function and it should all come together. So I came up with this: Code: function handleSelected2(opt,category) { for (var h = 0; h <gpolylines.length; h++) { gpolylines[h].hide(); } h = opt.selectedIndex - 1; if (h > -1) { gpolylines[h].show(); } for (var v=0; v<pts.length; v++) { show(category); } } which gets me lines, but no arrows. You can see it sort of working he http://www.xelawho.com/map/zonesarrowstest.htm I figure I've got to be close, because if I just tell it to show all the arrows (without going through the category filter) like this: Code: function handleSelected2(opt,category) { for (var h = 0; h <gpolylines.length; h++) { gpolylines[h].hide(); } var h = opt.selectedIndex - 1; if (h > -1) { gpolylines[h].show(); } for (var i=0; i<pts.length; i++) { pts[i].show(); } } then all the arrows show up, as you can see he http://www.xelawho.com/map/zonesarrowstest2.htm I'm not getting any error messages and I've tried pretty much everything I can think of... I've been tweaking this for days and it's driving me crazy. Does anybody else have any ideas? Thanks in advance. Hi everyone, I am pretty new at javascript OOP. I have a javascript file that has plenty of javascript functions, variables, arrays, etc. I need to convert this into an object. Here is an example: Code: var myvar1 = ''; var myvar2 = new array(); var myvar3 = new array(); var myvar4; var myvar5 = 60; var myvar6 = ''; function myfunc1(){ myvar1 = 'hello'; return myvar1; } function myfunc2(somenum=0){ myvar5 = somenum; //calling myfunc1() from within this function. //do something in here } function myfunc3(){ //calling myfunc1() from within this function. for(i=0;i<somelength;i++){ myvar2 = myvar3[i]; (something to put into the array) } } 1. I need to create an object and put ALL the varibles (myvar1 - myvar5) in that object. 2. Then the first two functions "myfunc1 and myfunc2" inside the same object. 2. And the function myfunc3 needs to sit OUTSIDE my object as a regular javascript function. It calls on myfunc1 (which is inside the object) and also inserts data into myvar2 (which is classified inside the object) and myvar3 (which is classified inside the object as well). This is what i came up with, but it's not going well: Code: var myobj1 = function(){ this.myvar1 = ''; this.myvar2 = new array(); this.myvar3 = new array(); this.myvar4; this.myvar5 = 60; this.myvar6 = ''; var myfunc1 = function(){ this.myvar1 = 'hello'; return this.myvar1; } var myfunc2 = function(somenum=0;){ this.myvar5 = somenum; //calling this.myfunc1() from within this function. //do something in here } } function myfunc3(){ //calling mynewobj.myfunc1() from within this function. for(i=0;i<somelength;i++){ mynewobj.myvar2 = mynewobj.myvar3[i]; (something to put into the array) } } var mynewobj = myobj1; HELP.....!!!! i really want to get into object oriented world, so thanks in advance. Hello again! Is there any way to pass a function(with its parameters) to another function using a parameter? Examples: Here is how I do it now: PHP Code: function output(text){ alert(text); } function bla(text, func){ output(text); } bla("Text is here", output) //Outputs "Text is here" I only want to pass the function to bla() as a parameter. I need something like this: PHP Code: function output(text){ alert(text); } function bla(func){ output(); } bla(output("Text is here")) //Outputs "Text is here" Is this possible in some way? Thanks in advance. |