JavaScript - Eval Function Assignment
Hi All,
This is my function function outputSelected() { alert(window.opener.document.forms[0].txt11_19.value); alert(window.opener.document.forms[0].rdo11.length); var questionID = document.forms[0].cntQuestion.value; var choiceID = document.forms[0].cntChoice.value; var txtValue = document.forms[0].strEmpNo.value + " " + document.forms[0].strName.value; alert(txtValue); var leftValue = 'window.opener.document.forms[0].txt' + questionID + '_' + choiceID + '.value =' + txtValue; eval(leftValue); } all the alerts work as expected. bu the eval function does not. error: expected ';' any ideas what is happening. or is there any other way of doing this. Similar TutorialsHi - I wrote some code that uses the eval function. I am in the process of rewriting the code to improve on it where possible (a learning exercise). I have read that eval is evil because of security concerns and that the eval'd code is not compiled prior to runtime. I don't think my use of eval presents a security concern. However, I wonder if there is some way to replace the eval function with a more natural technique. I have done this using eval(); also using a new Function method. I have tried using a window[] method but I can't get that to work. OK, on the the actual code: The purpose of the javascript is to count keystrokes. I have a bunch of global counter variables declared in this fashion: Code: MyLib.CountQ=0; MyLib.CountW=0; MyLib.CountE=0; MyLib.CountR=0; MyLib.CountT=0; MyLib.CountY=0; MyLib.CountU=0; MyLib.CountI=0; MyLib.CountO=0; MyLib.CountP=0; When the Count function is called I want to update the appropriate counter. Thus: MyLib.Count'+varkeyname+'+=1; Where varkeyname is 'q' or 'w' or 'e' etc. Code: //MyLib is a global variable namespace. function Count() {//updates counters var varkeyname= specialchars(MyLib.KeyName);//identity of the key pressed. var stra="Count"+varkeyname;// string used to change an html value. //var strb=eval("MyLib.Count"+varkeyname+"+=1");//original eval function that worked just fine. var strb='return MyLib.Count'+varkeyname+'+=1';//string to update a counter. var myfunc= new Function(strb);//Function intended to replace the eval function - this also works just fine. document.getElementById(stra).value = myfunc(); ... You can see that I have replaced the eval function with another function - but since this is also not compiled prior to runtime I don't think this is an improvement. I have read about using the window[string] method but I can't get it to work. This is not a critical issue but I'd appreciate any comments. Thanks, Jim Hi, i want a page with rotation of images, with fading. I'm trying with two images, but i see only the first image. Firebug console give me this error: Quote: $ is not defined: eval ('div =$("#focus_'+categoria+'")'); This is the entire code: Code: <script type="text/javascript"> array_img_2 = Array(); array_img_2[0] = 'PhpLib/../upload/2-Galleria/ima_galleria_03.gif'; array_img_2[1] = 'PhpLib/../upload/2-Galleria/ima_galleria_02.gif'; </script> <noscript>...</noscript> <div id="focus_2"> <a href="index.php?cp=4" title="vai alla gallery"> <img width="924" alt="immagini dei prodotti" src="PhpLib/../upload/2-Galleria/ima_galleria_03.gif" /></a> </div> <script src="PhpLib/jquery-1.2.6.min.js" type="text/javascript"> </script> <script type="text/javascript"> categories = Array(); categories[0]='2'; var numvisible_2 = 0; function changeImage(categoria){ var d = document; var aux = parseInt(eval('numvisible_'+categoria)); var array_img = eval('d.MM_'+categoria); if (array_img.length>1){ var img_index =(aux+1)%array_img.length; var div,img; eval ('div =$("#focus_'+categoria+'")'); eval ('img =$("#focus_'+categoria+' img")'); var control = "url('"+ array_img[img_index].src+"')"; $(div).css('background-image', control); $(img).animate({opacity:0.01},3000,function(){ this.src = array_img[img_index].src; $(img).animate({opacity:1},1000); }); eval ("numvisible_"+categoria+"=img_index"); } } function Init_Focus(){ var j; for (j=0; j<categories.length; j++) { var categoria = categories[j]; var array_img = eval('array_img_'+categoria); MM_preloadImages(array_img, categoria); setInterval("changeImage("+categoria+")",5000); } } function MM_preloadImages(img, categoria) { //v3.0 var d=document; eval("d.MM_"+categoria+"= new Array()"); var i,j=0; var a = img; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ eval("d.MM_"+categoria+"[j]=new Image"); eval("d.MM_"+categoria+"[j++].src=a[i]"); } } Init_Focus(); </script> Hi All, I have a problem in which I try to execute a funcition via a document.write() and it throws an "object expected" error. Overall I am making an interface for MS ACCESS .mdb table via ADODB using JavaScript and I want to be able to click on a link and the id is used to delete that entry. Code: My function is: Code: function deleteRecord(del) { var adoConn = new ActiveXObject("ADODB.Connection"); var adoRS = new ActiveXObject("ADODB.Recordset"); adoConn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source = {path to }knowBA.mdb'"); adoRS.Open("Select * From know where ID="+ del, adoConn, 1, 3); adoRS.Delete; adoRS.Close(); adoConn.Close(); } The code using the funcition is - oh and the numric KEY is rs(0) : Code: if(!rs.bof) { document.write("<table width='700' border='1' align='center' cellpadding='2' cellspacing='0' bgcolor='#FFFFFF'>"); rs.MoveFirst() while(!rs.eof) { document.write("<tr><td><div align='center'><strong>"+rs(1)+"</strong></div>"); document.write("<strong>Keyword(s):</strong> "+rs(3)); document.write("<br><strong>Entry:</strong> " +rs(2)+" "); document.write("<A HREF='javascript:onClick=("+"eval(deleteRecord(" +rs(0)+"))"+")'>delete</A> "); document.write("</td></tr>"); cnt=cnt+1; rs.MoveNext() } document.write("</table></form>"); } if (cnt==0){ alert ("Sorry, there are no results on that search.");} rs.close() cn.Close(); } </script> Thanks for any hints on how to accomplish this! Here is the assignment: Ocean Levels Assuming the ocean’s level is currently rising at about 1.5 millimeters per year, write a program that displays a table showing the number of millimeters that the ocean will have risen each year for the next 25 years. (we should use a "for" loop) Here is my code so far: <html> <head> <title>Ocean Page</title> <script type = "text/javascript"> var year, rise; document.write("Number of Years Ocean Level <br />"); year_str = alert("This will give you the prediction of ocean level rise for up to 25 years", ""); year_str= 25 year = parseFloat(year_str); rise_str = alert("The Ocean Rises at 1.5 milimeters a day", ""); rise_str = 1.5 rise_str = parseFloat(rise_str); r= parseFloat(rise_str) var MAX_VALUE = r; for (rise=1; rise <= r; ++rise ) { distance = rise * year document.write(year+" years   "+ distance+" ocean level <br />"); } </script> </head> <body> <h3>Click Refresh (or Reload) to run the script again</h3> <br /> </body> </html> END So far it just gives me years 25 ocean level 25. I can probably figure out how to create a table...but I'm having an issue getting the 1.5 to multiply 25 times. Any help? I'm a newby =) Thanks a million!!!!!!!!!!!! =) http://i50.tinypic.com/2njcxn5.png basically.. a button that changes the color of that box.. the font to bold.. and changes a frame from two search engine websites. Hello, in semester 2 of my first year of a Business Computer Systems. Anyway for my recent assignment I need to build a pretty basic shopping cart and have some cilent side validation as well. ----------------------------------------- Shopping Cart Anyway for the shopping cart do i have to: Item = goes into its own array Amount = goes into its own array price = goes into its own array then use a retrieve function to add each array into different sections in a table. and then simply times the amounts by their prices then add them all together using for loops? or can Item Amount = All in the same array. Price Then use a for loop to detect the correct data from the array for each section of the shopping cart? ----------------------------------------- Client Side Validation Presumably I just use simply javascript to detect phone numbers within a box form. i.e. (in simply english) if amount in phone form is < 11 then display alert. same for @ and . for email address? Hi, I have been working on a CS assignment that pertains to calculating the total cost (including tax) once a certain item is bought (there are a total of 4 different products). I can't get the code to work, so any help is much appreciated. Thank you. Question: Create a Web page that contains 1 text field and 1 button. The text field will be used to display the product/service ordered. Use a prompt window to get the user's name. Convert their name to proper case. Use an alert window to display a welcome message that includes their name. Use a prompt window to ask the user which one of four products/services they wish to purchase. Based on their input, calculate the tax and total cost for this product/service. Display the product/service ordered in the proper field. Then create bill. At the end, use the an alert window to display a message telling the user to click the browser's Back button to reload the page to start again. Code so far: Code: <html> <head> <title> Android World Products </title> <script type="text/javascript"> <!-- var fullName = ""; function askName() { fullName = prompt("Please Enter Your Name:"); var x = fullName.indexOf(" "); var firstName = fullName.substring(0,x); firstName = firstName.substring(0,1).toUpperCase() + firstName.substring(1); var lastName = fullName.substring(x+1); lastName = lastName.substring(0,1).toUpperCase() + lastName.substring(1); fullName = firstName + " " + lastName; if (x > -1) alert("Welcome " + fullName); else alert("Please try again."); } var evoPrice = 250.00; var optimusPrice = 200.00; var captivPrice = 150.00; var casePrice = 30.00; var products = new Array('HTC Evo 4G','LG Optimus S','Samsung Captivate','Leather Case'); var prices = new Array(evoPrice,optimusPrice,captivPrice,casePrice); var tax = 1.08375; var totalCost = 0; if(product==1) {totalCost = evoPrice + (evoPrice*tax); } else if(product==2) {totalCost = optimusPrice + (optimusPrice*tax); } else if(product==3) {totalCost = captivPrice + (captivPrice*tax); } else if(product==4) {totalCost = casePrice + (casePrice*tax); } return totalCost; } var seeBill = confirm("Click OK to See Your Bill"); if(seeBill) { Window = window.open("","Receipt","width=200,height=200"); Window.document.write("Android World <br>"); Window.document.write("Customer Name: "+Name+"<br>"); if(product=="1") {Window.document.write("Product: "HTC Evo 4G"<br>"); Window.document.write("Cost: $"evoPrice"<br>"); } else if(product=="2") {Window.document.write("Product: "LG Optimus S"<br>"); Window.document.write("Cost: $"optimusPrice"<br>"); } else if(product=="3") {Window.document.write("Product: "Samsung Captivate"<br>"); Window.document.write("Cost: $"captivPrice"<br>"); } else if(product=="4") {Window.document.write("Product: "Leather Case"<br>"); Window.document.write("Cost: $"casePrice"<br>"); } Window.document.write("Tax: 8.375%<br>"); Window.document.write("Your total cost for this purchase: $"totalCost"<br>"); Window.document.write("Thank you for shopping at Android World!"); function show_prompt() <input type=button value="Try it now" onClick="alert('Please use the browser's back button to reload the page')"> </script> </head> <body onload="askName ()"> <body style="background-color:#66FF66"> <h1> Android World Products </h1> <ol>Offered Products: <li>HTC Evo 4G: $250.00</li> <li>LG Optimus S: $200.00</li> <li>Samsung Captivate: $150.00</li> <li>Leather Case: $30.00</li> </ol> <br> <!--form name="Form" action="" method=""> <br> <input type="text" name="customer" onclick="typename()" /> <input type="button" name="" value="Confirm Your Purchase" onclick="" /> </form> </body> </html> First of all, Who's the best Javascript here?
Code: var i = 1; var obj = document.createElement("pStretch" + i); obj.id = "pStretch" + i; obj.className='circle_point drag'; eval("pStretch" + i + ".obj = ") = obj; document.body.appendChild(obj); Red does not work. What I want is to store all regarding DOM object into a property of another object named the same as id of that DOM object. What to do to make that work ? OK Once again not out to spam . I am confused on this assignment? this is what i need to do The Sieve of Eratosthenes An integer is a prime number if it is evenly divisible by only itself and 1. There are several ways to find all prime numbers within a given range of integers, and the Sieve of Eratosthenes is an algorithm for to do just that. It operates as follows: Create an array with all elements initialized to 1 (true). Array elements with prime subscripts will remain as 1. All other array elements will eventually be set to zero. Starting with array subscript 2 (subscript 1 must be prime), every time an array element is found whose value is 1, loop through the remainder of the array and set to zero every element whose subscript is a multiple of the subscript for the element with value 1. For array subscript 2, all elements beyond 2 in the array that are multiples of 2 will be set to zero (subscripts 4, 6, 8, 10, etc.); for array subscript 3, all elements beyond 3 in the array that are multiples of 3 will be set to zero (subscripts 6, 9, 12, 15, etc.); and so on. When this process is complete, the array elements that are still set to 1 indicate that the subscript is a prime number. These subscripts can then be printed. Write a script that uses an array of 1000 elements to determine and print the prime numbers between 1 and 999. Ignore element 0 of the array. Ok for anyone who may understand, what am i supposed to create as output? Am i supposed to get a one big chart of numbers? or do i get a forever flow of numbers? suggestions please I am not really looking for code, just want some idea of what am i supposed to make as output? thanks Hey there, so this is my first time using this website. I was wondering if anyone can help me resolve this problem. It is for my Website Development Class and I am going use this forum to help me understand the languages haha. But Anyways. My homework assignment I have to do is: Create a Web page named gpa.html that can be used to compute your grade point average given grades and hours for courses completed. The page should repeatedly prompt the user for course information, reading the course name, grade received, and credit hours for a particular course in a single dialog box. While the user is done inputting the information, it should display on the website like this: COURSE GRADE HOURS THL100 B+ 3 PHL107 A 3 ENG120 C+ 3 MTH245 A 4 CSC221 A 3 Total grade points = 58 Number of hours = 16 GPA = 3.625 So my problem is that when I tried to display it outside the while loop it only displays "NaN". Please Help and Thanks! Here is my code: <!DOCTYPE html> <html> <!-- gpa.html--> <head> </head> <body> <script type= "text/javascript"> document.write("Course - Grade - Credit Hours"); document.write("<br>"); var third; var total = 0; var total2 = 0; var total4 = 0; var t_hrs = 0; var user; while (user != "") { user = prompt("Hello User. Enter course name, grade, & credit hours (i.e CS3240 B+ 3), or click OK with no data to terminate."); var uInput = user.split(" "); document.write(uInput); document.write("<br>"); third = uInput[2]; t_hrs = parseInt(t_hrs) + parseInt(uInput[2]); if (uInput[1] == "A"){ letter2point = 4.0; } else if (uInput[1] == "B+"){ letter2point = 3.5; } else if (uInput[1] == "B"){ letter2point = 3.0;} else if (uInput[1] == "C+"){ letter2point = 2.5; } else if (uInput[1] == "C"){ letter2point = 2.0; } else if (uInput[1] == "D"){ letter2point = 1.0; } else if (uInput[1] == "F"){ letter2point = 0.0; } total = letter2point * third; total2 = total2 + total; total4 = total2 / t_hrs; } document.write(total4) </script> </body> </html> Reply With Quote 01-29-2015, 02:47 AM #2 felgall View Profile View Forum Posts Visit Homepage Master Coder Join Date Sep 2005 Location Sydney, Australia Posts 6,745 Thanks 0 Thanked 666 Times in 655 Posts If that antiquated JavaScript is what your course is teaching then I feel sorry for you. Just about every statement that you have there is listed on one of the "Bad Bits" pages of my Introducing JavaScript web site where it gives the reasons for not using those 20 year old code constructs in modern web browsers (which means IE5 and any browser more recent than that). A couple of suggestions to get you started. 1. The second document.write is not complete so everything from there onward is broken. 2. To convert to a number use Number((t_hrs) or (+t_hrs). If you must use parseint then always include the second parameter to specify the number base you are converting from parseInt(t_hrs, 10) - with regard to t_hrs it is a number to start with so doesn't even need this conversion. 3. Use === and !== instead of == and != as the two character versions don't always give the expected result where the three character versions always do. Hello everybody, could anyone offer an insight into why this isn't work please? It should be a simple project I was given at college but it stops near the end. The task is to ask a user for a word using a form, then spell it out backwards — stupid, but, hey — it's a lesson! Here's the code: Thanks. <h2>JavaScript exercise 4</h2> <p>Ask the user for a string of text. This must then be displayed in reverse. (For example, if the user enters the words "Hello World!" an alert dialog box should appear with "!dlroW olleH") </p> <form action="javascript: displaymessage();" method="get"> <p>Please enter a word: <input id="user_word" name="user_wrd" type="text"> <input type="submit" value="Submit"> </p> </form> <script> function displaymessage() { /*Set a variable for the user's word*/ var word_forward; /*Get the user's word from the from above and put it into the variable*/ word_forward = document.getElementById("user_word").value; /*Write the user's word from the variable to the page*/ document.write("<p>The word is: " + word_forward + ".</p>"); /*Calculate the length of the user's word*/ var word_length=word_forward.length; /*Write the length of the user's word to the page*/ document.write("<p>The word length is: " + word_length + " characters.</p>"); /*Subtract 1 from word length to allow for character index numbers starting from zero*/ word_length2=(word_length-1); /*Set a variable for the character index number*/ var char_num; /*Begin character index number countdown loop: loop start value / loop end value / increment*/ for(char_num=word_length2; char_num=0; char_num--) { /*Write word backwards using charAt*/ document.write("The word spelled backwards is: " + word_forward.charAt(char_num)); } } </script> In context, the following would be applied to an admin-only menu page under the WordPress Dashboard.(e.g. not for public access) Reading MUCH of the evils of eval() however, my use of it below appears nonetheless susceptible to injection attack, and I was hoping for suggestions as to better approach, as I myself am at something of a loss. PHP Code: <!-- as many as 15 of these per page --> <select class='glry_update' id='<?php echo $prd_tbl_id; ?>'> <option value=""> **** </option> <option value="syndicate">Syndicate</option> <option value="rescind">Rescind </option> <option value="feature">Feature </option> <option value="defeature">DeFeature</option> <option value="flag">Flag</option> <option value="deflag">DeFlag</option> <option value='edit'>Edit</option> <option value="drop">Delete</option> </select> PHP Code: //jQuery update of gallery item where $('.glry_update') is a select/dropdown input $('.glry_update').change(function() { var editId = $(this).attr('id');//corrisponds to record_id# in db Ex:"110" var call = $(this).val();//selected value Ex:"flag" $('#itemId').val(editId); //sole input(hidden) in form[editItem] $('#'+editId+' option[value=""]').attr('selected', true); //reuturn 'Select' to default state if(call == 'edit') $('#editItem').submit();// return record detail page for editing if(call == 'drop') { var cnfm = 'Do your really want to delete this item'; if (confirm(cnfm)) drop(editId,'glry'); else return false; } else { var functCall= call+'('+editId+')'; // Ex: flag(110) alert(functCall);return false; // DANGER? --- DANGER! --- DANGER? --- DANGER! --- eval(functCall); // DANGER? --- DANGER! --- // DANGER? --- DANGER! --- DANGER? --- DANGER! --- } }); ok tell me if I wrote this properly Code: eval('windowBody' + windowCount + '.style.backgroundColor = "black";'); I'm attempting to be able to create multiple windows on my page http://opentech.durhamcollege.ca/~in...rittains/labs/ Hi for purpose of learning only. Stretching myself by looking at OOP in JSBible. In the book he used a frameset which I hate so I changed to innerHTML. I have two issues A) the code uses eval (highlighted)--- i'd like to not use that but I can't work out how to change it. B) how to show selected ie Earth when the page loads. I've tried loads of ways but just not getting it. here is full code working Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>OOP test PLANETS</title> <style type="text/css"> .highlight{ color:orange; font-weight:bold; } </style> <script type="text/javascript"> //* <![CDATA[ //define method function showPlanet(){ var result = ''; result += "Planet: <span class='highlight'>"+this.name+"</span><br />"; result += "Diameter: <span class='highlight'>"+this.diameter+"</span><br />"; result += "Distance from Sun: <span class='highlight'>"+this.distance+"</span><br />"; result += "One Orbit Around Sun: <span class='highlight'>"+this.year+"</span><br />"; result += "One Revolution (Earth Time): <span class='highlight'>"+this.day+"</span>"; var insert = document.getElementById("myinsert"); insert.innerHTML = result; } function planet(name,diameter,distance,year,day){ this.name = name; this.diameter = diameter; this.distance = distance; this.year = year; this.day = day; this.showPlanet = showPlanet; //showPlanet func now a method of planet } //create new planet objects in series of variables var Mercury = new planet("Mercury","3100 miles","36 million miles","88 days","59 days"); var Venus = new planet("Venus","7700 miles","67 million miles","225 days","244 days"); var Earth = new planet("Earth","7920 miles","93 million miles","365.25 days","24 hours"); var Mars = new planet("Mars","4200 miles","141 millon miles","687 days","24 minutes"); var Jupiter = new planet("Jupiter","88.640 miles","483 million miles","11.9 years","9 hours 50 minutes"); var Saturn = new planet("Saturn","74,500 miles","886 million miles","29.5 yeras","10 hours 39 minutes"); var Uranus = new planet("Uranus","32,000 miles","1.782 billion miles","84 years","23 hours"); var Neptune = new planet("Neptune","2.793 billion miles","165 years","15 hours","48 minutes"); var Pluto = new planet("Pluto","1500 miles","3.67 billion miles","248 years","6 days, 7 hours"); function planetInfo(which){ i = which.selectedIndex; //how to get same result without using eval eval(which.options[i].text + ".showPlanet()"); } //*/// ]]> </script> </head> <body> <h1>Daily Planet</h1> <form> <select name="planetList" id="planetList" onchange="planetInfo(this)"> <option>Mercury</option> <option>Venus</option> <option selected="selected">Earth</option> <option>Mars</option> <option>Jupiter</option> <option>Saturn</option> <option>Uranus</option> <option>Neptune</option> <option>Pluto</option> </select> </form> <div id="myinsert"> </div> </body> </html> Hi All, Am new to Javascript but fluent in C++ and other languages, I have a query, i made a global variable to hold string information, can the value of this string be assigned to a form input field value? I mean in the 'default value sense' I am just wondering if there is any syntax to accomplish this. EG in my javascript i have the string nameVal; It is a global variable, i would like to know if it is poosible access its value for use in the line below shown with italics, or is it basically always a case of 'type the value in manually yourself' and then rely on events functions to update the field thereafter? Code: Name: <br><input type = "text" name = "nameField" size = "50" value = my string val here onChange ="this.value=storeVal(this.value, '0')"></input></br> |