JavaScript - 1st Javascript Assignment
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? Similar TutorialsHi, 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?
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> 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. 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!!!!!!!!!!!! =) 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 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. So I was asked to input a recipe coding into my page, so that when you get the output of the servings, it's multiplied by what I put in the code. Here is the assignment : http://webct.dvc.edu/SCRIPT/COMSC100...C100_5059_FA11.. it's assignment # 7 and here is my coding ; html> <head> <title> COMSC 100 Assignment 7 by John Doe [1190802] </title> <script> function getInputAsText(_id){return document.getElementById(_id).value} function getInputAsNumber(_id){return parseFloat(document.getElementById(_id).value)} function setOutput(_id, _value){document.getElementById(_id).value = _value} function calculate() { // declare all variables var amount1 var amount2 var amount3 var amount4 var amount5 // get variable's value first = getInputAsNumber("first") second = getInputAsNumber("second") third = getInputAsNumber("third") fourth = getInputAsNumber("fourth") fifth = getInputAsNumber("fifth") // perform conversions amount1=amount1 / servingsBase * servingsNeeded amount2=amount2 / servingsBase * servingsNeeded amount3=amount3 / servingsBase * servingsNeeded amount4=amount4 / servingsBase * servingsNeeded amount5=amount5 / servingsBase * servingsNeeded // write output value setOutput("servingsBase", servingsNeeded) } </script> </head> <body> Recipe Converter:<br> To change the recipe for each<br> type the amount of each ingrediant<br> type the amount of servings<br> click go<br> converted amounts will where original amounts we <br> <br> Input AND Output values:<br> For this many servings: <input id="first"> sugar:<input id="second"><br> milk:<input id="third"><br> food:<input id="fourth"><br> water:<input id="fifth"><br> <input type="submit" value="go" onclick="calculate()"><br> </body> </html> what am I doing wrong?! my teacher is no help at all! ugh Hey, I'm taking a javascript class and have to do an assignment in which I'm supposed to show countdowns to various events. I have 2 files, an external js file and a html file. But I can't get it to work I've searched the forum and googled it but all the solutions I've found do not work. Here's the code. .js file: Code: /* New Perspectives on JavaScript, 2nd Edition Tutorial 2 Review Assignment Author: Date: Function List: showDateTime(time) Returns the date in a text string formatted as: mm/dd/yyyy at hh:mm:ss am changeYear(today, holiday) Changes the year value of the holiday object to point to the next year if it has already occurred in the present year countdown(stop, start) Displays the time between the stop and start date objects in the text format: dd days, hh hrs, mm mins, ss secs */ function showDateTime(time) { var date = time.getDate(); var month = time.getMonth()+1; var year = time.getFullYear(); var second = time.getSeconds(); var minute = time.getMinutes(); var hour = time.getHours(); ampm = (hour < 12) ? " a.m." : " p.m."; hour = (hour > 12) ? hour - 12 : hour; hour = (hour == 0) ? 12 : hour; minute = minute < 10 ? "0"+minute : minute; second = second < 10 ? "0"+second : second; return month+"/"+date +"/"+year+" at "+hour+":"+minute+":"+second+ampm; } function changeYear (today, holiday) { var year = changeYear.getFullYear(); holiday.setFullYear(year); year = (today > holiday) ? year + 1 : year; year = holiday.setFullYear(year); } function countdown(start, stop) { time = stop - start; seconds = Math.floor(time/1000); minutes = Math.floor(seconds/60); hours = Math.floor(minutes/60); days = Math.floor(hours/24); return days + " days," + hours + " hours," + minutes + " mins," + seconds + " secs"; } And here's the HTML file: Code: <?xml version="1.0" encoding="UTF-8" ?> <!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> <!-- New Perspectives on JavaScript, 2nd Edition Tutorial 2 Review Assignment Events in Tulsa Author: Date: Filename: events.htm Supporting files: dates.js, logo.jpg, tulsa.css --> <title>Upcoming Events at Tulsa</title> <link href="tulsa.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="dates.js"></script> <script type="text/javascript"> showCountdown(){ var today = new Date("October 31, 2010 10:00:00"); var Date1 = new Date("January 14, 2011 10:00:00"); var Date2 = new Date("May 21, 2011 12:00:00"); var Date3 = new Date("July 4, 2011 9:00:00"); var Date4 = new Date("September 1, 2011 12:00:00"); var Date5 = new Date("December 1, 2011 11:30:00"); var Date6 = new Date("December 31, 2011 3:30:00"); document.eventform.thisDay.value = showDateTime(today); changeYear(today, Date1); changeYear(today, Date2); changeYear(today, Date3); changeYear(today, Date4); changeYear(today, Date5); changeYear(today, Date6); document.eventform.count1.value = countdown(today, Date1); document.eventform.count2.value = countdown(today, Date2); document.eventform.count3.value = countdown(today, Date3); document.eventform.count4.value = countdown(today, Date4); document.eventform.count5.value = countdown(today, Date5); document.eventform.count6.value = countdown(today, Date6); } </script> </head> <body onload="setInterval('showCountdown()', 100)"> <form name="eventform" id="eventform" action=""> <div id="logo"> <img src="logo.jpg" alt="Tulsa Events" /> </div> <div id="links"> <a href="#">Home</a> <a href="#">City Services</a> <a href="#">City Agencies</a> <a href="#">Mayor's Office</a> <a href="#">News Today</a> <a href="#">Upcoming Events</a> <a href="#">Site Map</a> <a href="#">Search Engine</a> <a href="#">Public Notices</a> <a href="#">Survey Form</a> <a href="#">Contact Us</a> <a href="#">E-Government</a> </div> <div id="main"> <h3>Countdown to Upcoming Events</h3> <table> <tr> <th colspan="2" style="text-align: right">Current Date and Time</th> <td><input name="thisDay" id="thisDay" readonly="readonly" size="40" /></td> </tr> <tr> <th>Event</th> <th>Starting Time</th> <th>Countdown to Event</th> </tr> <tr> <td><input value="Heritage Day" readonly="readonly" size="20" /></td> <td><input value="Jan 14 at 10:00 a.m." readonly="readonly" size="20" /></td> <td><input name="count1" id="count1" size="40" /></td> </tr> <tr> <td><input value="Spring Day Rally" readonly="readonly" size="20" /></td> <td><input value="May 21 at 12:00 p.m." readonly="readonly" size="20" /></td> <td><input name="count2" id="count2" size="40" /></td> </tr> <tr> <td><input value="July 4th Fireworks" readonly="readonly" size="20" /></td> <td><input value="Jul 4 at 9:00 p.m." readonly="readonly" size="20" /></td> <td><input name="count3" id="count3" size="40" /></td> </tr> <tr> <td><input value="Summer Bash" readonly="readonly" size="20" /></td> <td><input value="Sep 1 at 12:00 p.m." readonly="readonly" size="20" /></td> <td><input name="count4" id="count4" size="40" /></td> </tr><tr> <td><input value="Holiday Party" readonly="readonly" size="20" /></td> <td><input value="Dec 1 at 11:30 a.m." readonly="readonly" size="20" /></td> <td><input name="count5" id="count5" size="40" /></td> </tr> <tr> <td><input value="New Year's Bash" readonly="readonly" size="20" /></td> <td><input value="Dec 31 at 3:30 p.m." readonly="readonly" size="20" /></td> <td><input name="count6" id="count6" size="40" /></td> </tr> </table> </div> </form> </body> </html> Thanks for your help, I appreciate it The goal is for selectedDay to be assigned the value of the system variable Mainpackage.subclass0.subclass1.firstDay and then incremented by two days. Mainpackage.subclass0.subclass1.firstDay needs to be unchanged. Important system variable in red. To be 'manipulated and used' variable in green. Even with an intermediary, third, dummy variable it doesn't work: Code: //Declarations and instantiations var systemDate = new Date(); var selectedDay = new Date(); Mainpackage.subclass0.subclass1.firstDay ; //Assignments and manipulations systemDate = Mainpackage.subclass0.subclass1.firstDay ; selectedDay = systemDate ; selectedDay .setDate( selectedDay .getDate()+2); //Logging console.log('Mainpackage.subclass0.subclass1.firstDay: ' +Mainpackage.subclass0.subclass1.firstDay +'\n' +'systemDate: ' +systemDate +'\n' +'selectedDay :' +selectedDay +'\n'); Console log is: Code: Mainpackage.subclass0.subclass1.firstDay: Tue Aug 24 2010 00:00:00 GMT-0400 (Eastern Daylight Time) systemDate: Tue Aug 24 2010 00:00:00 GMT-0400 (Eastern Daylight Time) selectedDay: Tue Aug 24 2010 00:00:00 GMT-0400 (Eastern Daylight Time) It doesn't work in my webapp : All variables change at the same time. 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> The suspect line is the following $('.leaveClan').attr('id') = <?php echo $id; ?>; the span with the class (there is only one) leaveClan is on the main page, and that line of javascript is on a page being called by AJAX within that page. Can anyone see why that is causing an error? Let me know if you need to see any more of the code Hello! I am trying to find a script that allows you to open multiple browser tabs and then close each of those tabs, either one by one or all at once. Does anyone know how to do this please? Thanks so much for your help. I want to have another go at Javascript. I have several books on the subject but I find that my eyesight is a major problem. Therefore I want to try an on-line solution, preferably free. I have Googled, but there are so many that I am almost dizzy with the choices. Perhaps someone could recommend one. Not too fussy visually. My knowledge is VERY basic. Frank Does anyone know how to make URL links that use Javascript still work when users have Javascript disabled on their browser? The only reason I'm using JS on a URL is because my link opens a PDF file, and I'm forcing it not to cache so users have the latest version. I tried the <script><noscript> tags, but I'm not sure if I'm using it correctly, as my URL completely disappears. Below is my HTML/Javascript code: <p class="download"> <script type="text/javascript">document.write("<span style=\"text-decoration: underline;\"><a href=\"javascript:void(0);\" onclick=\"window.open( 'http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf?nocache='+ Math.floor( Math.random()*11 ) );\" >The Child Magazines Media Kit</a></span> (PDF 1 MB) ");</script> <noscript><span style="text-decoration: underline;"><a href="http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf" >The Child Magazines Media Kit</a></span> (PDF 1 MB)</noscript> </p> Thanks for any help, Michael |