JavaScript - Function Not Accessing Global Array
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? 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? 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> 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: 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 am fairly new to Javascript. I have a function which takes a string which consists of key value pairs and sets a form control based on key being the form element name and value being the value to set. eg string could be "key1=orange;key2=2;key3=whetever" Here is the function: function processresponse(frm, serverResponse) { var items = serverResponse.split(";"); for(var i = 0; i < items.length; i++) { var item = items[i]; var eqchar = item.search("="); if(eqchar != -1) { var key = item.slice(0, eqchar); var value = item.slice(eqchar+1); var elemname = key; if(document.getElementById(elemname) != null) { var type = frm.elements[elemname].type; if (type=="checkbox") { value == "1" ? frm.elements[elemname].checked=true : frm.elements[elemname].checked=false; } else if (type=="text"){ //do processing for text (text input) frm.elements[elemname].value = value; } else if(type=="select-one"){ //only one is openformmode - default to [0] - true if(value == "0" || value.length == 0) { frm.elements[elemname].options[0].selected = true; } else { frm.elements[elemname].options[1].selected = true; } } else { alert("unknown ctrl type: " + type + " name: " + frm.elements[elemname].name + " val: " + value + " key: " + key); } } //if(frm.getElementById(elemname) } } } The problem line is: var type = frm.elements[elemname].type; elemname is case sensitive so if for example the form element is called dog and the string elemname is Dog, then the line fails with Error: 'elements[...].type' is null or not an object So my check if(document.getElementById(elemname) != null) is insufficient to guard against this. I realise I could do a try catch but there must be a more legant way than that. How can I test the formname more reliably? Any ideas would be very welcome. Angus I created an array, whose entries looks like this: [41, "The bird flew into it's cage"] [33, "He drew fire from Joe"] [33, "Roger asked her her name"] [2, "I am awfully happy"] . I want to pull the sentence item out of some array entries. E.g., in the second entry, namely, arrayName[1], what I thought was the second item (the sentence), I could manage by invoking arrayName[1][1] . But to my dismay, this doesn't do the trick. arrayName[1][1] actually delivers up the second CHARACTER of the entry (the number "3"). I thought the comma between the number and the sentence would separate the items, although I "pushed" each entry into the array as one single entry. How do I "grab" the whole sentence? How do I push both items separately to achieve "one entry"? 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! I am very new to javascript. I have a problem getting to any element from this form generated by the jsp page using struts. Please show me how to get to item[0].totalAmount for example, so that I can create a function to calculate the calculateTotal(). So far, when I do the alert, it is only valid up to document.myForm.item; the document.myForm.item[0] is invalid according to the alert. Any help is very much appreciated. function calculateTotal(){ alert(document.myForm.item); } <form name="myForm" method="post" action="/myAction.do"> <table id="display" border="1"> <tr> <th scope="col" id="totalAmount">Total Amount</th> <th scope="col" id="adjustmentAmount>Adjustment Amount</th> <th scope="col" id="newAmount">NewAmount</th> </tr> <tr> <td><input type="text" name="item[0].totalAmount" id="totalAmount" value="100" readonly="readonly"></td> <td><input type="text" name="item[0].adjustmentAmount" id="adjustmentAmount" value="" onblur="javascript:calculateTotal();" readonly="readonly"></td> <td><input type="text" name="item[0].newAmount" id="newAmount" value="" readonly="readonly"></td> </tr> <tr> <td><input type="text" name="item[1].totalAmount" id="totalAmount" value="350" readonly="readonly"></td> <td><input type="text" name="item[1].adjustmentAmount" id="adjustmentAmount" value="" onblur="javascript:calculateTotal();" readonly="readonly"></td> <td><input type="text" name="item[1].newAmount" id="newAmount" value="" readonly="readonly"></td> </tr> </table> </form> Hi, I'm struggling with all this DOM stuff so I hope someone can help. I have a form with multiple input fields and I'm trying to identify the specific input field that is in focus so that I can display a relevant status bar message. I have a message array with various entries in it and I'm calling a showStatus() function with an onfocus function from the form itself e.g. The code in the input form = Code: <input type="text" name="first" size="31" maxlength="20" class="entry" onfocus="showStatus()"/> The showStatus() function so far is = Code: function showStatus() { var message = ['Please provide your First Name.', plus loads of other properley formatted status messages......] var x=document.getElementById().focus(); window.status = message[x]; } I'd like to access the array variable of the item that is in focus not only for the message but also for an onblur function to validate input. Any ideas? My thanks R I'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. I've been trying for several hours to solve this University problem but I'm just unable to get it done. I'm supposed to create a function that takes an array with all the A,B,C,D ... and shift them one place to the right (for instance array of A,B,C,D should be shifted and be like D,A,B,C - the last character goes to first position) Here is the code that I've been dealing with: Code: var abcArray = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; function shift(anyArray) { var newArray = Array(anyArray.length); for (var position = 0; position < newArray.length; position = position + 1) { if (position == 0) { newArray[position] = anyArray[anyArray.length - 1]; } else { newArray[position] = anyArray[position - 1]; } } anyArray = newArray; } shift(abcArray); document.write(abcArray); If I remove the function and try this code directly on the array it does work, but when I use the code as it is just like you see - the function shift doesn't change the Array and doesn't shift the values inside one position to the right and I have no clue why. Anyone has some ideas?! I would like to pass an array to a function but how does the program know which array I would like to choose from?? Lets say I have 3 arrays and I would like to pass array C, to my function. I checked the web but they only show if you have ONLY 1 array but NOT for multiple arrays. How would I even go about doing this?? Code: var arrA=new Array("fox.com","nbc.com","abc.com", "google.com"); var arrB=new Array("car","bike","boat", "plane"); var arrC=new Array("1","2","3", "4", "5", "6", "7", "8", "9"); function display(myArray){ myArray[1] = "changed"; } display(myArray); document.writeln(myArray[1]); thanks Hi all, I have a question about following code. It is tested as working well but the problem is that I need to catch values of array registos from javascript function getData(dataSource, sql_str) in PHP and not only update values of each form element. Can you help me, plz? Code: <script language = "javascript"> function getData(dataSource, sql_str){ if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ var registos = eval('('+xmlhttp.responseText+')'); document.getElementById("id_1").value=registos["cliente"]; document.getElementById("id_2").value=registos["designacao"]; } } xmlhttp.open("GET", dataSource+"&sql_str="+sql_str,true); xmlhttp.send(); } </script> <?php $sql_str="SELECT cliente, designacao WHERE cliente = '$cliente'"; $record=$db->sql_query($sql_str); list($registos[cliente], $registos[designacao]) = $db->sql_fetchrow($record); echo "<form id=\"form\">"; echo "<input type=\"text\" id=\"id_1\" name=\"registos[cliente]\" value=\"".$registos[cliente])."\">"; echo "<br>"; echo "<input type=\"text\" id=\"id_2\" name=\"registos[designacao]\" value=\"".$registos[designacao]."\">"; echo "<br>"; echo "<input type=\"button\" value=\"CONFIRMAR\" onclick=\"getData('mysql_query.php', '".base64_encode(serialize($sql_str))."')\">"; echo "</form>"; Hello there, I was having some trouble with 2D arrays (or array of arrays). Essentially, the array has 100 rows, with two columns. The first column of every row holds a name, and the second holds a sales amount. With the use of a do while loop, the user can continuously add up to 100 names and sales amounts. After all the information the user wishes to add is stored into the 2D array I'm attempting to pass that very same 2D array as a parameter to a function called printRow as can be seen in the code below: Note: the function call and the actual function are found in two separate javascripts. Code: var salesPerson=new Array(100) for (i=0; i <=100; i++) { salesPerson[i]=new Array(2); } var x = 0; do { salesPerson[x][0] = getName(); salesPerson[x][1] = getSales(); x++; }while(x != 100 && confirm("Enter more employee information?")); printRow(salesPerson[][]); Code: function getName() { var nameEntered = prompt("What is your first name?"); return nameEntered; } function getSales() { var error; var salesEntered; do { salesEntered = prompt("What were your sales?"); error = false; if (isNaN(salesEntered) || salesEntered == null || salesEntered == "") error = true; }while(error); return salesEntered; } function printRow(salesPerson[][]) { for (i =0; i<salesPerson.length; i++) { document.write(salesPerson[i][0] + " " + salesPerson[i][1]); } } At the moment I'm only looking to print the contents of the 2D array that I pass as a parameter to the document. As is, the javascipt doesn't seem to execute at all, it worked fine up until I added the printRow function call and function which leads me to believe I may not be passing it as a parameter correctly. Any tips on how to do this correctly would be greatly appreciated! 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/ Another homework assignment that I can't quite seem to get to work... I've been asked to do the following using javascript: -Create a function named randInt() with one parameter of "size". Declare a variable named "rNum" equal to a random integer between 1 and the value of the size variable. Return the value of the "rNum" varialbe from the function. -Create a function named getQuote() with one parameter anemd "qNum". The function should create an array named mtQuotes with five quotes; there should be no quote for the array index "0". Return the value of the mtQuotes array for the qNum index. - In the div element of "quotes" insert a script with the following commands: Declare a variable named "randValue" which is euqal to a random integer between 1 and 5 (use the randInt() function). Declare a variable named "quoteText" containing the quote whose array index value is equal to randValue. Write the value of quoteText to the web page. Here is what I have...it returns undefined. thanks. Code: <html> <head> <script type="text/javascript"> function randInt(size) { var rNum=Math.ceil(Math.random()*5); return(rNum); } </script> <script type="text/javascript"> function getQuote(qNum); var mtQuotes = new Array(); mtQuotes[0] = ""; mtQuotes[1] = "I smoke in moderation, only one cigar at a time."; mtQuotes[2] = "Be careful of reading health books, you might die of a misprint."; mtQuotes[3] = "Man is the only animal that blushes or needs to."; mtQuotes[4] = "Clothes make the man. Naked people have little or no influence on society."; mtQuotes[5] = "One of the most striking differences between a cat and a lie is that a cat has only nine lives."; return mtQuotes[qNum]; </script> </head> <body> <div id="quotes"> <script type="text/javascript"> var randValue=randInt(5); var quoteText=getQuote(randValue); document.write(quoteText); </script> </div> hello all, I am new to javascript, i just wanted to know how can i send a array from perl to javascript function.... if anybody having any idea about this please reply me..thanks in adbvance I'm trying to pass titleArray and pointsArray to the task(); I'm getting an error mgs this.assignments() is not a function. I've highlighted this.assignments() Code: <html> <head> <title>Variable - Examples 1</title> <script type="text/javascript"> function Student(firstName, lastName, email, courseID, titleArray, pointsArray){ this.firstName = firstName; this.lastName = lastName; this.email = email; this.courseID = courseID; this.title = titleArray; this.points = pointsArray; this.assignments = task; this.totalPoints = addExam; this.finalGrade = calcGrade; } Student.prototype = { constructor : Student, toString : studentInfo }; var t = this.title; var p = this.points; function task(t, p){ var title = this.t; var points = this.p; var titlePoints = ""; for (var i=0; i < points.length; i++){ titlePoints += title[i] + " : " + points[i] + "<br>"; } return titlePoints; } function addExam(){ var assignments = [30, 30, 28, 27, 29]; var exams = [41,45]; var highOfTwo = Math.max(41,45); var sum = 0; for (var i=0; i < assignments.length; i++){ sum += assignments[i]; } return sum + highOfTwo; } var totalPoints = addExam(); function calcGrade(){ var grade; if (totalPoints >= 190){ return "A+"; }else if (totalPoints >= 180){ return "A"; }else if (totalPoints >= 175){ return "B+" }else if (totalPoints >= 170){ return "B"; }else if (totalPoints >= 165){ return "B-"; }else if (totalPoints >= 160){ return "C"; }else if (totalPoints >= 150){ return "D"; }else if (totalPoints < 150){ return "F"; } } function studentInfo(){ return "Student : " + this.lastName + "," + this.firstName + "<br>"+ "eMail : " + this.email + "<br>" + "Course ID : " + this.courseID + "<br>" + "--------------------------------" + "<br>" + this.assignments() + "--------------------------------" + "<br>" + "Total Points : " + this.totalPoints() + "<br>" + "Final Grade : " + this.finalGrade(); } var titleArray = ["Assignment1","Assignment2","Assignment3","Assignment4","Assignment5","MidTerm", "Final"]; var pointsArray = [30, 30, 28, 27, 29, 41, 45]; var student = new Student("FirstName", "Lastname", "myemail@gmail.com","COIN-070B.01", titleArray, pointsArray ); </script> </head> <body> <script type="text/javascript"> document.writeln(student.toString()); </script> </body> </html> |