JavaScript - Cant Do Easy Javascript Program
I am trying to create a javascript program that will assign a number based on a score. If the grade (number) is 90 or above it assigns a 4, if it is in the 80's its assigned a 3, etc.
So far: Code: <<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> ITS200 Project 6: Quality Points </title> <script type = "text/javascript"> <!-- function QualityPoints() { var form = document.getElementById( "form" ); var input = parseInt( form.number.value); form.points.value = (input >= 0 && input <= 100) Number(input): "Error"; } // end function function Number(grade) { if (grade >= 90) return 4; else if (grade >=80) return 3; else if (grade >=70) return 2; else if (grade >=60) return 1; else return 0; } // end Number function // --> </script> </head> <body> <form id = "form" action = ""> <table border = "1"> <tr> <td> Enter Grade </td> <td> <input name = "number" type = "text" /> </td> <td> <input type = "button" value = "Get Quality Points" onclick = "QualityPoints()" /> </td> </tr> <tr> <td> Quality Points </td> <td> <input type = "text" name = "points" /> </td> </tr> </table> </form> </body> </html> Where do I go from here? I have no idea whats wrong. Similar TutorialsHi im trying to make a program that passes an array to a method. the method then finds the smallest number in the array and passes that number back to the main where its printed out. I am getting an error saying: "error: number cannot be resolved to a variable". I am using drjava. here is my code. Code: import java.util.*; public class homeWorkTwo{ public static void main(String[] args) { int[] arrayA; arrayA = new int[10]; arrayA[0]=7; arrayA[1]=5; arrayA[2]=8; arrayA[3]=9; arrayA[4]=2; arrayA[5]=10; arrayA[6]=11; arrayA[7]=1; int lowestNumber = find_sum(number); System.out.print("The smallest number is: "+lowestNumber); } public static int find_sum(int [ ] arrayB){ int isItSmaller=0; int small=0; System.out.println("poop"); for(int i=0;i<=7;i++){ isItSmaller=arrayB[i]; if(small<isItSmaller){} else small=isItSmaller; } System.out.print(small); return small; } } Hello people CF, I need some help with this Javascipt program that im trying to make. Ill provide you with the algorithm i have made and the javascript code. I only know basic javascripting and i had a lot of help with this. I need help getting the javascript code for comparing last date modified, renaming the copied file with last date modified, also i can get it to copy 1 file, but i need it to loop through all the files in the given folder. Algorithm Code: // get source and destination folder path // check if folder exists // if source folder exists, continue with the process, otherwise display an error message // if destination folder exists, proceed with transferring the files // get the file collections in the source folder // loop through each file to check if the file has been modified // if the file exists, check file attributes to the source file; 32 means file has changed // if file has changed, // compare the last date modified of the source and destination file // if the source last date modified is greater than the destination last date modified then // rename the destination file by appending the last date modified // to its file name and then transfer the lastest file from the source folder // otherwise, no need to copy the file and move to the next file // otherwise, do nothing and move on to the next file // otherwise, create a folder first before proceeding with transferring the files I had a lot of help with this Code: <HTML> <HEAD> <TITLE>FileSystem Object Demo</TITLE> <SCRIPT> Language = "JavaScript"> <!--hide from old browsers function checkExistingFolder(folder) { var FS = new ActiveXObject("Scripting.FileSystemObject"); return FS.FolderExists(folder); } function createFolder(folder) { var FS = new ActiveXObject("Scripting.FileSystemObject"); FS.createFolder(folder); document.write ("<BR>New folder created."); } function copyFile(source, dest) { var FS = new ActiveXObject("Scripting.FileSystemObject"); FS.copyFile(source + "\\Test.txt", dest + "\\Test.txt"); document.write ("<BR>File Copied."); } function runProgram () { var from = document.getElementById('from').value; var to = document.getElementById('to').value; var isExist = checkExistingFolder(to); alert(isExist); if(isExist) document.write("Folder Exists, checking last date modified........"); else { document.write("Folder doesn't exist."); createFolder(to); } copyFile(from, to); } // --> </SCRIPT> </HEAD> <BODY background="1330843076080.jpg"> <CENTER> <H1>FileSystem Object Demo</H1> FROM: <input type="text" id="from" value=""/> TO: <input type="text" id="to" value="d:\\test"/> <input type="button" onClick="runProgram()" value="Transfer Files"/> <SCRIPT LANGUAGE = "JavaScript"> <!--hide from old browsers // --> </SCRIPT> </CENTER> </BODY> </HTML> For class NumericQuestion Add setAnswer, a method that takes a double as input, converts it to a string and calls setAnswer in the superclass Question to store the answer. o Add checkAnswer, a method that takes an answer in string form, converts it to a double, gets the correct answer in string form from Question, converts it to a double, and returns true if they are within 0.01 of each other and false otherwise. For class quiz Change main so that all three questions are asked. presentQuestion that prints out the correct answer, only when the answer is wrong public class NumericQuestion { private String text; private Double answer; /** * Constructs a question with empty question and answer. */ public NumericQuestion() { text = ""; answer = 3.1416; } /** * Sets the question text. * @param questionText the text of this question */ public void setText(String questionText) { text = questionText; } /** * Sets the answer for this question. * @param correctResponse the answer */ public void setAnswer(Double correctResponse) { answer = correctResponse; } /** * Checks a given response for correctness. * @param response the response to check * @return true if the response was correct, false otherwise */ public boolean checkAnswer(String response) { return response.equals(answer); } /** * Displays this question. */ public void display() { System.out.println(text); } } import java.util.Scanner; public class Quiz { public static void main(String[] args) { Question first = new Question(); first.setText("What inherits data and behavior from a superclass?"); first.setAnswer("subclass"); ChoiceQuestion second = new ChoiceQuestion(); second.setText("Which modifies the object on which it operates in some way?"); second.addChoice("Accessor", false); second.addChoice("Mutator", true); second.addChoice("Method", false); second.addChoice("Variable", false); NumericQuestion third = new NumericQuestion(); third.setText("What is the numeric value for PI?"); third.setAnswer(3.1416); presentQuestion(first); presentQuestion(second); //presentQuestion(third); } /** Presents a question to the user and checks the response. @param q the question */ public static void presentQuestion(Question q) { q.display(); System.out.print("Your answer: "); Scanner in = new Scanner(System.in); String response = in.nextLine(); System.out.println(q.checkAnswer(response)); } } I'm very new at Javascript and writing programs so I'm not sure if this is even possible to do. I want to write a program that allows someone to select four tasks from a dropdown menu. The tasks are each 1 hour long. I want the program to calculate the number of hours and display that information below the tasks. I also want the person to be able to add or remove tasks. I get how to save tasks and display the results but I don't know how to calcuate the number of hours. Any suggestions? Here is what I have so far: Code: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Four Tasks</title> <style> body { background-color:silver; font-family:Arial, Helvetica, sans-serif; font-size:1.2em; } h1 { font-family:Arial, Helvetica, sans-serif; font-size:1.4em; } </style> <script> function storeTask(task) { var taskDetail = document.getElementById(task).value; localStorage.setItem(task, taskDetail); } function getTask(task) { document.getElementById(task).value = localStorage.getItem(task); } function clearTask(task) { localStorage.removeItem(task); document.getElementById(task).value=""; } function displayTasks() { outputResults = document.getElementById("Results"); outputResults.innerHTML = 'Task 1: ' + localStorage.getItem('task1') + '<br />' + 'Task 2: ' + localStorage.getItem('task2') + '<br />' + 'Task 3: ' + localStorage.getItem('task3') + '<br />' + 'Task 4: ' + localStorage.getItem('task4') + '<br />' + ''; } </script> </head> <body> <table width="100%"> <tr> <td valign="top"> <div id="outer"> <h1>Four Tasks</h1> My To Do List: <br><br> Task 1: <select id="task1"> <option>Laundry</option> <option>Cooking</option> <option>Dishes</option> <option>Water Plants</option> <input type="button" value="Save" onclick="storeTask('task1');"> <input type="button" value="Clear" onclick="clearTask('task1');"> <br><br> Task 2: <select id="task2"> <option>Laundry</option> <option>Cooking</option> <option>Dishes</option> <option>Water Plants</option> <input type="button" value="Save" onclick="storeTask('task2');"> <input type="button" value="Clear" onclick="clearTask('task2');"> <br><br> Task 3: <select id="task3"> <option>Laundry</option> <option>Cooking</option> <option>Dishes</option> <option>Water Plants</option> <input type="button" value="Save" onclick="storeTask('task3');"> <input type="button" value="Clear" onclick="clearTask('task3');"> <br><br> Task 4: <select id="task4"> <option>Laundry</option> <option>Cooking</option> <option>Dishes</option> <option>Water Plants</option> <input type="button" value="Save" onclick="storeTask('task4');"> <input type="button" value="Clear" onclick="clearTask('task4');"> </div> </td> <td valign="top"> My Tasks: <br> <input type="button" value="Display tasks" onclick="displayTasks();"> <div id="Results"></div> </td> </tr> </table> </body> </html> Hi! frnds, I was wondering if you could help me with the JavaScript programing... Every possible help will be appreciated I am very new to the world of programming and JavaScript but I have some Ideas which I would like to execute and I will learn anything and everything in the way to accomplish them... Program: user end: the page is about users priorities and displaying back the selected... the program work as a user reaction based comparison module... where the priorities stored in the program are shown 2 at a time and lets user to select what is more important to him and stores the result in another variable than that variable is shown with another variable which is already stored and the result out of that is stored in another new variable and so on.. in the end it show the result of important selected priorities... 1) say there are 6 variables storing string values: Code: <script type = "text/javascript"> var p1 = "Doctors appointment"; var p2 = "studying for the exam"; var p3 = "Going out for most awaited shopping"; var p4 = "Login on Facebook"; var p5 = "Replying to text msgs"; var p6 = "Go out with friends"; 2) there are two sections on the html document: i) where the variables are displayed dynamically and changes the value on click.. it works like a comparison where user selects (onclick) what is more important to him shows the next value and so on... in the end stores the result... functioning(I have no I idea how to do this): say on the html document only two variables are displayed at first and than the user selects one of it as more important to him so the result is stored in another new variable than that new variable is shown with the third stored variable and once one of them is selected it is stored in another new variable and is compared with forth stored variable and so on till the last selected is stored as the result1... all comparisons must happen on the same div of the html document procedure has to loop three times till 3 results (result1, result2, result3) out of six are selected more important... result1 has to be removed from the next loop for result 2 as result1 is already selected important by the user.. result1 and result2 are to be removed from the next loop for result 3 as they are already selected important by the user ii) the second section displays important 3 results (result1, result2, result3) selected by him... my friend told jQuery can do the dynamic comparison part but I don't know how to use it... the logic of creating new variable for storing result and then comparing can be improved or changed... Please help I have an homework for a web development class. I wrote a program that would be displayed on a webpage that returns the users zodiac sign. It was working just fine until i made small mistake somewhere but i just can't find it. If anyone could help I would appreciate it, I imagine it would be a very easy job for anyone familiar with javascript. [CODE] function signs() { var date=document.zodiac.date.value; var month=document.zodiac.month.selectedIndex; var fortune= new Array() fortune[0]="There is a true and sincere friendship between you and your friends. " fortune[1]="You find beauty in ordinary things, do not lose this ability. " fortune[2]="Ideas are like children; there are none so wonderful as your own. " fortune[3]="It takes more than good memory to have good memories. " fortune[4]="A thrilling time is in your immediate future. " fortune[5]="Your blessing is no more than being safe and sound for the whole lifetime. " if (document.zodiac.month.value == 1 && document.zodiac.date.value >=20 || document.zodiac.month.value == 2 && document.zodiac.date.value <=18) {document.zodiac.sign.value = "Aquarius";} if (document.zodiac.month.value == 1 && document.zodiac.date.value > 31) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 2 && document.zodiac.date.value >=19 || document.zodiac.month.value == 3 && document.zodiac.date.value <=20) {document.zodiac.sign.value = "Pisces";} if (document.zodiac.month.value == 2 && document.zodiac.date.value > 29) {document.zodiac.sign.value = "Invalid Date?";} if (document.zodiac.month.value == 3 && document.zodiac.date.value >=21 || document.zodiac.month.value == 4 && document.zodiac.date.value <=19) {document.zodiac.sign.value = "Aries";} if (document.zodiac.month.value == 3 && document.zodiac.date.value > 31) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 4 && document.zodiac.date.value >=20 || document.zodiac.month.value == 5 && document.zodiac.date.value <=20) {document.zodiac.sign.value = "Taurus";} if (document.zodiac.month.value == 4 && document.zodiac.date.value > 30) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 5 && document.zodiac.date.value >=21 || document.zodiac.month.value == 6 && document.zodiac.date.value <=21) {document.zodiac.sign.value = "Gemini";} if (document.zodiac.month.value == 5 && document.zodiac.date.value > 31) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 6 && document.zodiac.date.value >=22 || document.zodiac.month.value == 7 && document.zodiac.date.value <=22) {document.zodiac.sign.value = "Cancer";} if (document.zodiac.month.value == 6 && document.zodiac.date.value > 30) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 7 && document.zodiac.date.value >=23 || document.zodiac.month.value == 8 && document.zodiac.date.value <=22) {document.zodiac.sign.value = "Leo";} if (document.zodiac.month.value == 7 && document.zodiac.date.value > 31) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 8 && document.zodiac.date.value >=23 || document.zodiac.month.value == 9 && document.zodiac.date.value <=22) {document.zodiac.sign.value = "Virgo";} if (document.zodiac.month.value == 8 && document.zodiac.date.value > 31) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 9 && document.zodiac.date.value >=23 || document.zodiac.month.value == 10 && document.zodiac.date.value <=22) {document.zodiac..sign.value = "Libra";} if (document.zodiac.month.value == 9 && document.zodiac.date.value > 30) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 10 && document.zodiac.date.value >=23 || document.zodiac.month.value == 11 && document.zodiac.date.value <=21) {document.zodiac.sign.value = "Scorpio";} if (document.zodiac.month.value == 10 && document.zodiac.date.value > 31) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 11 && document.zodiac.date.value >=22 || document.zodiac.month.value == 12 && document.zodiac.date.value <=21) {document.zodiac.sign.value = "Sagittarius";} if (document.zodiac.month.value == 11 && document.zodiac.date.value > 30) {document.zodiac.sign.value = "Invalid Date";} if (document.zodiac.month.value == 12 && document.zodiac.date.value >=22 || document.zodiac.month.value == 1 && document.zodiac.date.value <=19) {document.zodiac.sign.value = "Capricorn";} if (document.zodiac.month.value == 12 && document.zodiac.date.value > 31) {document.zodiac.sign.value = "Invalid Date";} document.getElementById("image").src=document.zodiac.sign.value+".jpg" var randomFortune= Math.floor(Math.random() * 5) document.zodiac.fortunebox.value=fortune[randomFortune] document.getElementById('body').style.backgroundColor='#99FFCC' document.getElementById('body').style.backgroundColor='#99FFCC' document.tags.H1.color = '#99FFCC' } [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> <div style="background-color:#000000; height:60px;" > <h1 align="center"> What Zodiac Sign Are You? </h1> </div> <title>Horoscope Fortune Teller</title> <LINK REL=StyleSheet HREF="horoscope.css" TYPE="text/css" MEDIA=screen> <script type="text/javascript" src="Horoscope.js"> </script> </head> <body id=body> <br> <br> <table border=10px; align="center", height="250px"> <form name="zodiac"> <tr><td>Please select your day and month of birth to get started:</td></tr> <br> <br> <tr> <td>Choose month from the list:</td> <td> <select name="month"> <option value="1">January</option> <option value="2">February</option> <option value="3">March</option> <option value="4">April</option> <option value="5">May</option> <option value="6">June</option> <option value="7">July</option> <option value="8">August</option> <option value="9">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> </td> </tr> <tr> <td>Enter day of birth:</td> <td><input type="text" name="date" value="Day" onClick=value=""></td> </tr> <tr> <td>Your Zodiac Sign is:</td><td><input type="text" name="sign" value="Zodiac Sign"></td> </tr> <tr> <td><input type="button" value="Click to find your sign" onClick="signs()"></td> <tr><td><img src="" id="image" alt="" /></td><td align="center"><input type="text" name="fortunebox" value="" size="80"></td></tr> </tr> </table> </form> <br> <br> <br> <br> <div style="background-color:#000000; height:60px;"></div> </body> </html> Hello I am trying to send some values in combobox2 depending on one value selected in combobox1. Both are in php. Following is the code for combobox1 - Code: <td><div id="Gen_Core"> <?php $sql="SELECT t.Main_CoNo, t.Main_CoName FROM Main_Course t WHERE t.Modl_No ='2' and t.Main_CoName NOT IN (SELECT t1.Course_Name from Course t1 where t.Modl_No = t1.Module_ID and Student_ID='$Stud_ID')"; $result=mysql_query($sql); $options=""; while (@$row=mysql_fetch_array($result)) { $id=$row["Main_CoNo"]; $name=$row["Main_CoName"]; $options.="<OPTION VALUE=\"$id\">".$name.'</option>'; } ?><select size="4" style="width:100px; font-size: 10px;" name="classes[]" id="class_list" onClick="return validateForm()"><?=$options?></select></div></td> Here is Javascript program - <script type="text/javascript"> function validateForm() { var gen=document.forms["select"]["classes"].value; alert("hi"); } </script> If I select one value from this combobox1, I want to send that value to java script program which is not working...It is not going to Javascript program at all.. I tried couple of things like onClick, onSubmit in form, in select etc. But it seems nothing is working... What I want is - If one option is selected from combobox1, then javascript program should recognize it and send values for combobox2. How will I do it? Really confused..... I am very new to coding. The below is an assignment for a class. It is a "game" which is supposed to do the following: When your program starts up it must display the image that will move around, a Start button, a Stop button, and a way for the user to specify an interval before a new game begins. The default interval must be 1000 msec. When the user presses Start, a new game starts and the selected image is displayed at a random place. The image must move to a new random place once per interval. If the user presses the Stop button, the image must stop moving, and a subsequent Start must start everything over from the beginning. Each time the user successfully hits the image, the program must move the image to a new random place immediately (i.e., not wait for the current interval to end). When the user has hit the image 3 times, the program must display a confirm dialog box that reports the elapsed time and that also says something like "Another game?" If the user pushes OK, that starts a new game immediately (no need to push Start again). If Cancel is pushed, the program stops. I have been working on this for hours, but it does not work properly. Obvious issues: the game starts running when the page loads, instead of when the start button is pushed. The confirm at the end does not cause a new game to start. The time/ elapsed time calculations are not functioning properly/ the elapsed time always displays as 1 sec. Code: <html> <title> Dori's WhaM Game </title> <head> Stephen Salutes You </head> <body> <br> <img id="Colbert" src="StephenColbert.jpeg" style="position:absolute; left:10px; top:85px" onClick='hit()'> <form> <input type=button value="Start game." onClick='newgame()'> <input type=button value="Stop it, stop it now." onClick='clearInterval(setint_val); return true;'> <br> Desired speed is <input type=text id=interval value="1000" size=5> msec </form> <script> var hitcount= 0 var setint_val = (setInterval('moveit()', document.getElementById("interval").value)); var starttime var endtime function newgame() { clearInterval(setint_val) hitcount= 0 setInterval() starttime=new Date().getTime() } function moveit() { document.getElementById("Colbert").style.left = 800 * Math.random() + "px"; document.getElementById("Colbert").style.top = 500 * Math.random() + "px"; } function hit() { moveit() clearInterval(setint_val) setInterval() hitcount= hitcount + 1 if (hitcount >= 3) { clearInterval (setint_val); // clearInterval() to stop the image from moving endtime=new Date().getTime(); alert(starttime) alert (endtime) // compute the elapsed time (make another call to new Date()) if (confirm("That took " + endtime-starttime+" seconds. Would you like to try again?")) { newgame ()} else {clearInterval (setint_val) hitcount=0} }} </script> </body> </html> hi all, i have created one program using javascript.i have written using javascript functions.. can u tell me what is the problem with my program i have saved it as messages.js,but the script is not executing can u tell me what went wrong..... below is my javascript program..... Code: // form validation function // function checkName(form) { var eobj=document.getElementById('realnameerror'); var sRealName = form.realname.value; var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i; var error=false; eobj.innerHTML=''; if (sRealName == '') { error='Error: Username cannot be blank!'; } else if (sRealName.length < 4) { error="UserName should be atleast 4 characters long"; } else if (!oRE.test(sRealName)) { error="Incorrect format."; } if (error) { if (hasFocus == false) { form.realname.focus(); hasFocus = true; } eobj.innerHTML=error; return false; } return true; } function checkEmail(form) /* for email validation */ { var eobj=document.getElementById('emailerror'); eobj.innerHTML=''; var error = false; if (form.email.value.length == 0) { error = 'Please enter email.'; } else if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.email.value)) { return true; } else { error = 'Invalid E-mail Address! Please re-enter.'; } if (error) { eobj.innerHTML=error; if (!hasFocus) { form.email.focus(); hasFocus = true; } return false; } return true; } function validatePwd(form) /* password & retype-password verification */ { var eobj1=document.getElementById('passworderror'); var eobj2=document.getElementById('password2error'); var minLength=6; var invalid=' '; var pw1=form.password.value; var pw2=form.password2.value; var error=false; eobj1.innerHTML=''; eobj2.innerHTML=''; if (pw1.length<1) { error='Please enter your password.'; } else if (pw1.length < minLength) { error='Your password must be at least ' + minLength + ' characters long. Try again.'; } else if (pw1.indexOf(invalid) > -1) { error='Sorry, spaces are not allowed.'; } else if (pw2.length == 0) { error='Please retype password.'; if (!hasFocus) { form.password2.focus(); hasFocus = true; } eobj2.innerHTML=error; return false; } if (error) { if (!hasFocus) { form.password.focus(); hasFocus = true; } eobj1.innerHTML=error; return false; } if (pw1 != pw2) { eobj2.innerHTML=' passwords not matching.Please re-enter your password.'; if (!hasFocus) { form.password2.focus(); hasFocus = true; } return false; } return true; } function validPhone(form) /* phone no validation */ { var eobj=document.getElementById('phonenoerror'); var valid = '0123456789'; var phone = form.phoneno.value; var error=false; var i=0; var temp; eobj.innerHTML=''; if (phone == '') { error='This field is required. Please enter phone number'; } else if (!phone.length > 1 || phone.length < 10) { error='Invalid phone number length! Please try again.'; } else { for (i=0; i < phone.length; i++) { temp = '' + phone.substring(i, i + 1); if (valid.indexOf(temp) == -1) { error='Invalid characters in your phone. Please try again.'; } } } if (error) { if (!hasFocus) { form.phoneno.focus(); hasFocus = true; } eobj.innerHTML=error; return false; } return true; } function validate() { hasFocus = false; var form = document.forms['form']; var ary=[checkName,checkEmail,validatePwd,validPhone]; var rtn=true; var z0=0; for (var z0=0;z0<ary.length;z0++) { if (!ary[z0](form)) { rtn=false; } } return rtn; } // START OF MESSAGE SCRIPT // var MSGTIMER = 20; var MSGSPEED = 5; var MSGOFFSET = 3; var MSGHIDE = 3; // build out the divs, set attributes and call the fade function // function inlineMsg(target,string,autohide) { var msg; var msgcontent; if(!document.getElementById('msg')) { msg = document.createElement('div'); msg.id = 'msg'; msgcontent = document.createElement('div'); msgcontent.id = 'msgcontent'; document.body.appendChild(msg); msg.appendChild(msgcontent); msg.style.filter = 'alpha(opacity=0)'; msg.style.opacity = 0; msg.alpha = 0; } else { msg = document.getElementById('msg'); msgcontent = document.getElementById('msgcontent'); } msgcontent.innerHTML = string; msg.style.display = 'block'; var msgheight = msg.offsetHeight; var targetdiv = document.getElementById(target); targetdiv.focus(); var targetheight = targetdiv.offsetHeight; var targetwidth = targetdiv.offsetWidth; var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2); var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET; msg.style.top = topposition + 'px'; msg.style.left = leftposition + 'px'; clearInterval(msg.timer); msg.timer = setInterval("fadeMsg(1)", MSGTIMER); if(!autohide) { autohide = MSGHIDE; } window.setTimeout("hideMsg()", (autohide * 1000)); } // hide the form alert // function hideMsg(msg) { var msg = document.getElementById('msg'); if(!msg.timer) { msg.timer = setInterval("fadeMsg(0)", MSGTIMER); } } // face the message box // function fadeMsg(flag) { if(flag == null) { flag = 1; } var msg = document.getElementById('msg'); var value; if(flag == 1) { value = msg.alpha + MSGSPEED; } else { value = msg.alpha - MSGSPEED; } msg.alpha = value; msg.style.opacity = (value / 100); msg.style.filter = 'alpha(opacity=' + value + ')'; if(value >= 99) { clearInterval(msg.timer); msg.timer = null; } else if(value <= 1) { msg.style.display = "none"; clearInterval(msg.timer); } } // calculate the position of the element in relation to the left of the browser // function leftPosition(target) { var left = 0; if(target.offsetParent) { while(1) { left += target.offsetLeft; if(!target.offsetParent) { break; } target = target.offsetParent; } } else if(target.x) { left += target.x; } return left; } // calculate the position of the element in relation to the top of the browser window // function topPosition(target) { var top = 0; if(target.offsetParent) { while(1) { top += target.offsetTop; if(!target.offsetParent) { break; } target = target.offsetParent; } } else if(target.y) { top += target.y; } return top; } // preload the arrow // if(document.images) { arrow = new Image(7,80); arrow.src = "images/msg_arrow.gif"; } What is the best program or website for compressing Javascript? Optimally, I would like it to optimize variable and function names. I also have a tiny bit of PHP in the code, so it would be nice if it could recognize that but not a big deal if it can't. Thanks in advance for the suggestions! I am having trouble with JavaScript code and do not know why it is not working. I have the code I think is right but it is not showing up in my browser when run. Any ideas? Also are there any other ways to read in an xml file using javascript? please list if so. Thanks to codingforums that help me to gain success with my javascript program! Please let me know what do you think about it: http://backslash.altervista.org/messa/mass_search.html The js script read the page http://backslash.altervista.org/messa/orari_messa.html and get the church's data and the mass's time. I know it'll better use a db but i have no control on server where the html page is (the mine is only a copy) and i want to do something that if the owner of the server want put in, it can without problem. Any review will be very appreciated Thanks ps: look at the footer pps: sorry it's all in italian i am new in programming and learning it from lynda but i am trying to make a program which according to me is good enough but its not working and i am using free javascript editor for compiling and coding <!DOCTYPE html> <html> <body> <script> var a = 5; var b = 10; var c = 30; var d = a + b + c; alert("the value of d is" + d); </body> </html> Please tell me where is it i am making mistake Reply With Quote 01-08-2015, 11:56 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts You forgot the </script> ending tag. Hello all out there I am going to post this in 2 separate views. I am working on an assignment from this link http://books.google.ca/books?id=aG_T2aD ... MonthCell()&source=bl&ots=EJXyGF-tbI&sig=vbgqgua2uSaL6DWp0Rx_BYoZ0z8&hl=en&ei=9C7gTLmiAYaXnAeywLWRDw&sa=X&oi=book_result&ct=result&re snum=1&ved=0CBcQ6AEwAA#v=onepage&q=writeMonthCell()&f=false if u scroll down to case 1 is what I am working on included in the case are 2 other files as to the one i have to work on i used all the proper steps and instructions and i think I have the correcting coding for my form however my program still does not work here is the exact code i am using let me know if anyone sees any errors, as I am convinced i have it correct? Here is my code: <html> <head> <!-- New Perspectives on JavaScript Tutorial 3 Case Problem 1 The Lighthouse Author: John Res Date: November 14 2010 Filename: clist.htm Supporting files: lhouse.css, list.js, logo.jpg --> <title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> <script type"text/javascript" src"list.js"></script> <script type="text/javascript"> function amountTotal() { // return sum of values to amount array total=0; for(var i=0; i<amount.length; i++) { // set variable to 0 total+=amount[i]; } return total; } </script> </head> <body> <div id="title"> <img src="logo.jpg" alt="The Lighthouse" /> The Lighthouse<br /> 543 Oak Street<br /> Delphi, KY 89011<br/> (542) 555-7511 </div> <div id="data_list"> <script type=”text/javascript”> // set up variables of rows and cellspaces document.write(“<table border=’1′ rules=’rows’ cellspacing=’0′>”); document.write(“<tr><th>Date</th><th>Amount</th><th>First Name</th>”); document.write(“<th>Last Name</th><th>Address</th></tr>”); for (i=0; i< amount.length; i++) { // create a loop in counter of variable starting at 0 and increase of 1 increments if (i%2==0) document.write(“<tr>”); else document.write(“<tr class=’yellowrow’>”); // have every row with a yellow background use a loop document.write(“<td>”+date[i]+”</td>”); document.write(“<td class=’amt’>”+amount[i]+”</td>”); // have values of the dates document.write(“<td>”+firstName[i]+”</td>”); document.write(“<td>”+lastName[i]+”</td>”); document.write(“<td>”); document.write(street[i]+”<br />”); document.write(city[i]+”, “+state[i]+” “+zip[i]); // zip arrays for address document.write(“</td>”); document.write(“</tr>”); } document.write(“</table>”); </script> </div> <div id="totals"> <script type=”text/javascript”> // use script elements in HTML document.write(“<table border=’1′ cellspacing=’1′>”); document.write(“<tr><th id=’sumTitle’ colspan=’2′>Summary</th></tr>”); document.write(“<tr><th>Contributors</th>”); document.write(“<td>”+amount.length+”</td></tr>”); document.write(“<tr><th>Amount</th>”); document.write(“<td>$”+amountTotal()+”</td></tr>”); document.write(“</table>”); </script> </div> </body> </html> thanks everyone I am attempting to create a javascript program for an imaginary airline reservation system. How its supposed to work is you type in 1 or 2 depending on which class you want and the program assigns you a seat. If seats are full, prompts come up for alternate classes. So far: Code: <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Airline Reservations System</title> <script type = "text/javascript"> <!-- var section; var seats = [ , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; var firstclass = 1; var economy = 6; var people = 0; function AssignSeat() { var SeatAssignment; if (people <=10) { section - parseInt( document.getElementById( "form" ).section.value); if (section == 1) { if ( firstclass <= 5 && seats [firstclass]== 0 ) { window.alert( "First Class.Seat #" + firstclass); seats[firstclass] - 1; // remove seat from first class ++people; //add person to variable ++firstclass; //add seat for first class } //end if else if (firstclass > 5 && economy <=10) { var conf = window.confirm("First Class is full. Would you like to sit in economy?" + "Click Cancel to wait for the next flight."); if (conf) { window.alert("Your seat assignment is" + economy); seats[economy] - 1; ++people; ++economy; } // end if else window.alert<"The next flight leaves in 3 hours."); } // end else if else window.alert("The next flight leaves in 3 hours."); } // end if else if (section ==2) { if (economy <= 10 && seats [economy] == 0) { window.alert("Economy. Seat # + economy); seats[economy] - 1; ++people; ++economy; } //end if else if (economy > 10 && firstclass <=5) { var conf - window.confirm("Economy is full. Would you like to sit in first class?" + "Click Cancel to wait for the next flight."); if (conf) { window.alert ("Your seat assignment is" + firstclass); seats[firstclass] - 1; ++people; ++firstclass; } // end if else window.alert("The next flight leaves in 3 hours."); } // end else if else window.alert("The next flight leaves in 3 hours."); } // end else if else window.alert("Error"); } // end if from line 21 } // end function // --> </script> </head> <body> <form id = "form" action = ""> <table border = "0"> <tr> <td> Please type 1 for First Class <br> Please type 2 for Economy </td> <td> <input name = "section" type = "text" size = "15" /> </td> <td> <input type = "button" value = "Make Reservation" onClick = "AssignSeat()" /> </td> </tr> </table> </form> </body> </html> No idea why it is not showing up!? hi ! i would like to write the code for multiple text box select as shown in the link below: http://www.downloadplex.com/Mobile/I...ne_284120.html please see the screen shot 3 The following quiz template only supports 4 possible answers. Id like to add a 5th answer. Should be quite easy to do, but I dont know any programming. http://javascript.about.com/library/blquizf.htm On the template above each possible answer can be given a different score. Then at the and it adds up the score and displays a message according to your total score. Thanks in advance Heres the code: The following is contained in file quizhead.js: var quiz = new Array(); var r = 0; var analPage = 'results.html'; quiz[r++] =('38901~16~What score would you give to your supervisor?~Bad~Average~Good~Excellent~1~4'); The following goes to on the page where the questions appear on the head section: <script src="quizhead.js" type="text/javascript"> </script> The following is contained in quizbody.js file: // Analysis Quiz Javascript // copyright 20th December 2004 - 13th May 2005, by Stephen Chapman // permission to use this Javascript on your web page is granted // provided that all of the code in this script (including these // comments) is used without any alteration function displayResult(cor) { document.write('<div style="font-size:14px;"><b>You have completed the quiz.<\/b><\/div><blockquote><span style="font-size:12px;">*<br \/>*<br \/>*<br \/>*<br \/><\/span><\/blockquote><div><a href="'+analPage+'?cor='+cor+'">Your result</a><\/div>'); } var qsParm = new Array(); function qs() { var query = window.location.search.substring(1); var parms = query.split('&'); for (var i=0; i<parms.length; i++) { var pos = parms[i].indexOf('='); if (pos > 0) { var key = parms[i].substring(0,pos); var val = parms[i].substring(pos+1); qsParm[key] = val; } } } qsParm['questnum'] = 0; qsParm['cor'] = 0; qs(); var questnum = qsParm['questnum']; var cor = qsParm['cor'];cor=cor%475; function checkAnswer(e,b,g){ var a = -1; var x = Math.floor(g/b); // x = bdca for (var i=0; i<e.c.length; i++) {if (e.c[i].checked) {a = i;}} if (a == -1) { alert("You must select an answer"); return false; } var b = new Array(); b[1] = Math.floor(x/1000); x -= b[1]*1000; b[3] = Math.floor(x/100); x -= b[3]*100; b[2] = Math.floor(x/10); b[0] = x - b[2]*10; cor += b[a]; var www = self.location.href.lastIndexOf('?'); var thispage = self.location.href; if (www != -1) thispage = self.location.href.substr(0,www); questnum++; var p = Math.floor((Math.random() * 8) + 2); var m = (p * 475) +cor; top.location = thispage + '?questnum='+ questnum +'&cor='+m; return false; } function result(cor) { var lo = 0, hi = 0; for (var i=0;i < quiz.length;i++) { var f = quiz[i].split('~'); lo += parseInt(f[7]); hi += parseInt(f[8]); } return Math.round((cor - lo) * 100 / (hi - lo)); } var tblsz = quiz.length; document.write('<table align="center" cellpadding="3" width="350" border="1"><tr>'); if (questnum < quiz.length) { var f = quiz[questnum].split('~'); document.write('<td align="left"><form name="myForm"><div style="font-size:14px;">Question: '+f[2]+'</div><blockquote><span style="font-size:12px;">\n'); document.write('<input type="radio" name="c" value="0" /> '+f[3]+'<br />\n'); document.write('<input type="radio" name="c" value="1" /> '+f[4]+'<br />\n'); if (f[5] != '') document.write('<input type="radio" name="c" value="2" /> '+f[5]+'<br />\n'); if (f[6] != '') document.write('<input type="radio" name="c" value="3" /> '+f[6]+'<\/span><\/blockquote>\n'); document.write('<div align="right"><input type="button" value="Next Question" onclick="checkAnswer(myForm,'+f[1]+','+f[0]+');return false;" /><\/div><\/form>\n'); } else { document.write('<td align="center">\n'); document.write('<form name="myForm">'); displayResult(result(cor)); document.write('<\/form>\n');} document.write('<\/td><\/tr><\/table>\n'); The following goes on the page where the questions appear on the body section: <script src="quizbody.js" type="text/javascript"> </script><noscript><table align="center" cellpadding="3" width="350" border="1"><tr> <td align="left"><div><b>This Quiz requires Javascript</b> </div><blockquote>You either have Javascript disabled <br />or the browser you are using does not<br /> support Javascript. Please use a Javascript<br /> enabled browser to access this quiz.<br /> <br /> </blockquote></td></tr></table></noscript> The following is contained in the quizresh.js file: // Analysis Quiz Javascript // copyright 20th December 2004, by Stephen Chapman // permission to use this Javascript on your web page is granted // provided that all of the code in this script (including these // comments) is used without any alteration var qsParm = new Array(); function qs() { var query = window.location.search.substring(1); var parms = query.split('&'); for (var i=0; i<parms.length; i++) { var pos = parms[i].indexOf('='); if (pos > 0) { var key = parms[i].substring(0,pos); var val = parms[i].substring(pos+1); qsParm[key] = val; } } } qsParm['cor'] = 0; qs(); var cor = qsParm['cor']; This goes on the page where the results are displayed on the head section: <script src="quizresh.js" type="text/javascript"> </script> The following is contained in the quizresb.js file: // Analysis Quiz Results if (cor <= 25) document.write('<p>Good<\/p>'); else if (cor <= 50) document.write('<p>Very Good<\/p>'); else if (cor <= 75) document.write('<p>Excellent<\/p>'); else document.write('<p>Perfect<\/p>'); This goes on the results page on the body section: <script src="quizresb.js" type="text/javascript"> </script> I need someone to make a small modification to this javascript code: <script type = "text/javascript"> function hyperlink() { var url = (location.href) url = url.replace(/\.(html)/i, "_2.html") window.location.href = url; } </script> Here is the situation: On this webpage: http://tehcake.com/video/30rock/2x14%20-%20Copyx.html where it says "Backup Links 1 2", if you click on the "1" in "Backup Links 1 2" it goes to this webpage, which is what it is supposed to do: http://tehcake.com/video/30rock/2x14%20-%20Copyx_2.html However, on this webpage, where it says "Backup Links 1 2", if you click on the "1" in "Backup Links 1 2" it leads to a non existing page by adding an extra "_2" to the end of the file name. Anyways, I need a way to modify this code (same one as above): <script type = "text/javascript"> function hyperlink() { var url = (location.href) url = url.replace(/\.(html)/i, "_2.html") window.location.href = url; } </script> This script subtracts ".html" and adds "_2.html" to the URL. Anyways, i need to change it so that if the filename has an _2.html in the file name, like in this URL: http://tehcake.com/video/30rock/2x14%20-%20Copyx_2.html the script would not add an extra _2 to the URL, instead it would just link to the same page. I dont know much about javascript so I need help to make this change. Hi I'm not a programmer if someone could help me fix this it would be great thanks. here is the code I found a while ago. Code: <!-- SUBMENU ROLLOVER SCRIPT --> <script type="text/javascript"> window.onload=function () { setStyles(); }; function setStyles() { ids = new Array ('contentMenu1','contentMenu2','contentMenu3','contentMenu4'); for (i=0;i<ids.length;i++) { document.getElementById(ids[i]).className='notactive'; document.getElementById(ids[i]).onclick=function() { return CngClass(this); } } } function CngClass(obj){ var currObj; for (i=0;i<ids.length;i++) { currObj = document.getElementById(ids[i]); if (obj.id == currObj.id) { currObj.className=(currObj.className=='notactive')?'active':'notactive'; } else { currObj.className='notactive'; } } //return false; } </script> <!-- END SUBMENU ROLLOVER SCRIPT --> and the html is here Code: <ul class="contentMenuContainer"> <li id="contentMenu1" class="notactive"><a href="javascript:ajaxpage('aj-wildlife.html', 'homeInfo');" onClick="setStyles('contentMenu1');" >wildlife</a></li> <li id="contentMenu2" class="notactive"><a href="javascript:ajaxpage('aj-solitude.html', 'homeInfo');" onClick="setStyles('contentMenu2');">solitude</a></li> <li id="contentMenu3" class="notactive"><a href="javascript:ajaxpage('aj-theboat.html', 'homeInfo');" onClick="setStyles('contentMenu3');">the boat</a></li> <li id="contentMenu4" class="notactive"><a href="javascript:ajaxpage('aj-hosts.html', 'homeInfo');" onClick="setStyles('contentMenu4');">your hosts</a></li> </ul> OK so all I need is to know how to set a list item to be class="active" by default. I tried setting it to "active" but the script must reset them all to "notactive". Sorry for being such a noob. Any help is greatly appreciated. thanks Help me anyone I am completely stuck. If you do this I shall build a shrine in your honour. In the following code the 'for' loop gets data from the relevant tags of an XML file, then puts them into the 'txt' variable. It then moves onto the next record in the XML file and does the same thing. However, I don't want the contents of txt to be overwritten each time the code loops through each record. Instead I want it to add to txt, then loop around and add the new contents of txt to the previous contents of txt. I tried txt = txt + artist + title + year; but this didn't work. Can anyone explain how to do this? Please note the contents of the variables are strings of text not numbers. Code: x=xmlDoc.getElementsByTagName("CD"); i=0; function displayCD() { for (var i=0;i<x.length;i++) { artist=(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue); title=(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue); year=(x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue); txt= "Artist: " + artist + "<br />Title: " + title + "<br />Year: "+ year; } document.getElementById("showCD").innerHTML=txt; } |