JavaScript - Question Concerning A Program Code
what does this code mean "obj.to"?
The code is here - Code: clearTimeout( obj.to ); I just want to know what does "to" mean here? Similar TutorialsHi I am new to programming and I am trying to write a piece of code, I need the output to be a whole random number, this is what I have up to now : <SCRIPT language = "JavaScript"> //generate a random number greater than or equal to 0.0 and less than 50.0 //and display it in an alert dialogue window.alert("getRoundedRandomNumber: " Math.round + Math.random()*50); </SCRIPT> </HEAD> <BODY> <STRONG>A test of the random number functions <BR></STRONG> <FORM NAME = "randomForm"> <INPUT TYPE = "button" NAME = "randomButton" VALUE ="Display Random Number" ONCLICK = "window.alert(getRoundedRandomNumber(50));"> </FORM> can anyone advise me where I would put the Math.round function and how to make it work ? Thanks in advance I am completely new to javascript but I have found a script that will do what I am looking to do. I do have one question about this script that I am sure one of you will have the answer to. Is there way to get the code below to run one time through the urls listed and then stop, without just restarting with the first url and running the script again. Thanks ahead of time for you answers. Code: Troy Wolf <troy@troywolf.com> Simply define your "slides" in the javascript slides[] array below. --> <html> <head> <title>SiteShow 1.0</title> <meta http-equiv="content-type" content="text/html; charset=windows-1250"> <style> /* Change body background-color to change fade out color. */ body.siteshow { margin:0; padding:0; background-color:#000000; } #menu { font-family:Arial; font-size:9pt; display:none; opacity:0.00; -mozopacity:0.00; filter:alpha(opacity=0); position:absolute; top:10px; left:10px; padding:5px; background-color:#000000; color:#FFFFFF; border:3px dotted #999999; } #menu a { color:#ffffff; } #menu a:hover { text-decoration:none; } #title { font-size:11pt; font-weight:bold; letter-spacing:2; } #slides { font-size:9pt; line-height:16pt; } .button { width:60px; font-size:9pt; letter-spacing:1; } </style> <script type="text/javascript"> var current_idx = 0; var slides = new Array(); var menuwin; var show_timer; var menu_timer; var menu; var content; var loaded = true; // Define your "slides". 3 values for each a // 1. Duration in seconds. // 2. Title to be used in menu. // 3. Source URL. Can be full URI or a relative URL. slides[1] = new Array(15, "WAMP HOWTO", "http://www.troywolf.com/articles/wamp_howto.htm"); slides[2] = new Array(15, "PHP Proxy", "http://www.troywolf.com/articles/php/class_http/proxy.phps"); slides[3] = new Array(15, "HTTP class", "http://www.troywolf.com/articles/php/class_http/"); slides[4] = new Array(15, "Session class", "http://www.troywolf.com/articles/php/class_session/"); slides[5] = new Array(15, "RSS Consumption", "http://www.troywolf.com/articles/php/class_xml/rss_example.php"); slides[6] = new Array(15, "PHP Exchange WebDAV", "http://www.troywolf.com/articles/php/exchange_webdav_examples.php"); slides[7] = new Array(15, "vCard class", "http://www.troywolf.com/articles/php/class_vcard/"); function MenuInit() { var html = ""; for(idx=1; idx<slides.length; idx++) { html += '<a href="javascript:Navigate('+idx+')">' + slides[idx][1] + "</a><br />\n"; } document.getElementById("slides").innerHTML = html; menu.style.display = "block"; } function MenuShow() { clearTimeout(menu_timer); opacity('menu', 0, 90, 500); menu_timer = setTimeout("MenuHide()", 3500); } function MenuHide() { opacity('menu', 90, 0, 500); } function Pause() { clearTimeout(show_timer); document.getElementById('play').style.display = "block"; document.getElementById('pause').style.display = "none"; } function Navigate(slide_idx) { clearTimeout(show_timer); if (current_idx == 0) { if (!slide_idx) { slide_idx = 1; } current_idx = slide_idx; content.src = slides[current_idx][2]; document.getElementById('play').style.display = "none"; document.getElementById('pause').style.display = "block"; show_timer = setTimeout("Navigate()", slides[current_idx][0]*1000); return; } if (slide_idx) { current_idx = slide_idx; content.src = slides[current_idx][2]; document.getElementById('play').style.display = "block"; document.getElementById('pause').style.display = "none"; return; } loaded = false; current_idx++; if ( current_idx == slides.length) { current_idx = 1; } opacity('content', 100, 0, 500); document.getElementById('play').style.display = "none"; document.getElementById('pause').style.display = "block"; show_timer = setTimeout("Navigate()", slides[current_idx][0]*1000); return; } function opacity(id, opacStart, opacEnd, millisec) { //speed for each frame var speed = Math.round(millisec / 100); var timer = 0; //determine the direction for the blending, if start and end are the same nothing happens if(opacStart > opacEnd) { for(i = opacStart; i >= opacEnd; i--) { setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); timer++; } if (opacEnd == 0) { setTimeout("FadeOutTrigger('"+id+"')",((timer-1) * speed));; } //if (opacEnd == 0) { FadeOutTrigger(id); } } else if(opacStart < opacEnd) { if (opacStart == 0) { FadeInTrigger(id); } for(i = opacStart; i <= opacEnd; i++) { setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed)); timer++; } } } //change the opacity for different browsers function changeOpac(opacity, id) { var object = document.getElementById(id).style; object.opacity = (opacity / 100); object.MozOpacity = (opacity / 100); object.KhtmlOpacity = (opacity / 100); object.filter = "alpha(opacity=" + opacity + ")"; } function FadeOutTrigger(id) { //alert('FadeOut: '+id); switch(id) { case "menu": document.getElementById(id).style.display = "none"; break; case "content": content.src = slides[current_idx][2]; //setTimeout("opacity('content', 0, 100, 500)", 1000); break; default: break; } } function FadeInTrigger(id) { //alert('FadeIn: '+id); switch(id) { case "menu": document.getElementById(id).style.display = "block"; break; case "content": //opacity('content', 0, 100, 500); break; default: break; } } function FadeInContent() { if (!loaded) { opacity('content', 0, 100, 500); loaded = true; } } function LoadTrigger() { //self.resizeTo(1366,768); menu = document.getElementById('menu'); content = document.getElementById('content'); Navigate(); MenuInit(); MenuShow(); } window.onload = LoadTrigger; </script> </head> <body class="siteshow"> <iframe id="content" name="content" style="width:100%; height:100%;" frameborder="no" scrolling="auto" src="" onmouseover="MenuShow();" onload="FadeInContent();" ></iframe> <div id="menu"> <div id="title">SiteShow Menu</div> <div id="slides"> </div> <p> <input id="pause" class="button" style="display:block;" type="button" value="pause" onclick="Pause()" /> <input id="play" class="button" style="display:none;" type="button" value="play" onclick="Navigate()" /> </p> </div> </body> </html> eeeeeee
I am trying to get a Javascript "script" to do a function for me. I am trying to write a a script that will run while the webpage is open, that is selected a randomized 9 digit number Less than 350000000 that will be put into a textbox and submitted. I want a adjustable time when it submits. Could this be made into an <iframe>? Also, this has to do it to a different website, not the one locally being opened. Thank you for your help. Hey guys, this should be a very easy fix for someone who knows Javascript (which I don't). The following code allows the class "ul.slideshow-nav li" to control the navigation of the slideshow, I want to adjust this script to allow "ul.slideshow-nav li" AND "ul.slideshow-nav2 li" to do this, possible? Code: $slideshow = { context: false, tabs: false, timeout: 8000, fx: 'scrollLeft', slideSpeed: 900, tabSpeed: 900, init: function() { this.context = $('#content-slideshow'); this.tabs = $('ul.slideshow-nav li', this.context); this.tabs.remove(); this.startSlideshow(); }, startSlideshow: function() { $('div.slideshow > ul', $slideshow.context).cycle({ fx: $slideshow.fx, pager: $('ul.slideshow-nav', $slideshow.context), pagerAnchorBuilder: $slideshow.startTabs, befo $slideshow.Tabactive, timeout: $slideshow.timeout, speed: $slideshow.slideSpeed, fastOnEvent: $slideshow.tabSpeed, pauseOnPagerHover: true, pause: true }); }, startTabs: function(i, slide) { return $slideshow.tabs.eq(i); }, Tabactive: function(currentSlide, nextSlide) { var activeTab = $('a[href="#' + nextSlide.id + '"]', $slideshow.context); if(activeTab.length) { $slideshow.tabs.removeClass('on'); activeTab.parent().addClass('on'); } } }; $(function() { $slideshow.init(); }); hello all i'm almost newbie to Javascript. i found this for instant search : demo : http://www.johnboy.com/scripts/insta...-php/index.php index.php PHP 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=iso-8859-1" /> <title>Instant Search With Arrow Key Navigation Using jQuery and PHP</title> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script type="text/javascript" src="search.js"></script> <script> //arrow key navigation $(document).keydown(function(e){ //jump from search field to search results on keydown if (e.keyCode == 40) { $("#s").blur(); return false; } //hide search results on ESC if (e.keyCode == 27) { $("#results").hide(); $("#s").blur(); return false; } //focus on search field on back arrow or backspace press if (e.keyCode == 37 || e.keyCode == 8) { $("#s").focus(); } }); // $(document).ready(function() { //clear search field & change search text color $("#s").focus(function() { $("#s").css('color','#333333'); var sv = $("#s").val(); //get current value of search field if (sv == 'Search') { $("#s").val(''); } }); // //post form on keydown or onclick, get results $("#s").bind('keyup click', function() { $.post("results.php", //post $("#search").serialize(), function(data){ //hide results if no more than 2 characters if (data == 'hide') { $('#results').hide(); } //show results if more than 2 characters if (data != 'hide') { $("#results").html(data); if (data) { $("#results").show(); } } }); }); // //hide results when clicked outside of search field $("body").click(function() { $("#results").hide(); }); // }); </script> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>Instant Search Using jQuery & PHP</h1> <h2>Example keywords (website, jquery, php, launch)<br /> <br /> </h2> <form id="search" name="search" method="post" action="" autocomplete="off"> <input name="s" type="text" id="s" value="Search" /> <div id="results"></div> </form> <br /> <br /> <br /> <a href="http://www.johnboy.com/blog/tutorial-instant-search-with-arrow-key-navigation-using-jquery-and-php">Back to Article & Source Code</a> </body> </html> results.php PHP Code: <?php require_once('mysql_connect.php'); //only show results if two or more characters have been typed - max of 50 characters $len = strlen(str_replace(" ","",$_POST[s])); //don't count blank spaces if ($len < 3 || $len > 50) { echo 'hide'; die; } // //get results if search string is longer than 3 characters if ($len > 3) { record_set('results', " SELECT news_title, news_heading, MATCH (news_title,news_text) AGAINST ('".strip_tags($_POST[s])."*' IN BOOLEAN MODE) AS ranking FROM jbp_blog_articles WHERE MATCH (news_title,news_text) AGAINST ('".strip_tags($_POST[s])."*' IN BOOLEAN MODE) AND news_type = 1 ORDER BY ranking DESC LIMIT 0,8 "); } ?> <ul> <!--display user's initial search term--> <li><a class="link" href="#" title="<?php echo $_POST[s]; ?>"><?php echo "$_POST[s]"; ?></a></li> <!----> <?php if ($totalRows_results) do { ?> <li><a class="link" href="/blog/<?php echo $row_results[news_heading]; ?>" target="_blank" title="<?php echo $row_results[news_title]; ?>"><?php echo "$row_results[news_title]"; ?></a></li> <?php } while ($row_results = mysql_fetch_assoc($results)); ?> </ul> search.js PHP Code: /* * Author: Marco Kuiper (http://www.marcofolio.net/) * Customizations by JBP noted in comments below */ var currentSelection = 0; var currentUrl = ''; // Register keydown events on the whole document $(document).keydown(function(e) { switch(e.keyCode) { // User pressed "up" arrow case 38: navigate('up'); break; // User pressed "down" arrow case 40: navigate('down'); break; // User pressed "enter" case 13: if(currentUrl != '') { window.location = currentUrl; } break; } }); // Add data to let the hover know which index they have for(var i = 0; i < $("#results ul li a").size(); i++) { $("#results ul li a").eq(i).data("number", i); } // Simulate the "hover" effect with the mouse $("#results ul li a").hover( function () { currentSelection = $(this).data("number"); setSelected(currentSelection); }, function() { $("#results ul li a").removeClass("search_hover"); currentUrl = ''; } ); function navigate(direction) { // Check if any of the menu items is selected if($("#results ul li .search_hover").size() == 0) { currentSelection = -1; } //JBP - focus back on search field if up arrow pressed on top search result if(direction == 'up' && currentSelection == 0) { $("#s").focus(); } // if(direction == 'up' && currentSelection != -1) { if(currentSelection != 0) { currentSelection--; } } else if (direction == 'down') { if(currentSelection != $("#results ul li").size() -1) { currentSelection++; } } setSelected(currentSelection); } function setSelected(menuitem) { //JBP - get search result to place in search field on hover var title = $("#results ul li a").eq(menuitem).attr('title'); $("#s").val(title); // $("#results ul li a").removeClass("search_hover"); $("#results ul li a").eq(menuitem).addClass("search_hover"); currentUrl = $("#results ul li a").eq(menuitem).attr("href"); } style.css PHP Code: #search { position:relative; display:block; height:35px; width:500px; padding: 0px; margin: 0px auto 0px auto; } #results { border:1px solid #CCCCCC; width:500px; display:none; z-index: 300; line-height:0; margin-top:-3px; margin-left: 0px; } #results ul { list-style:none; padding:0px; margin:0px; } #results ul li { background-color:#FFFFFF; text-align: left; } #results ul li:hover { background-color:#EBEBEB; } #results ul li a { line-height:20px; text-decoration:none; padding: 5px; display: block; color: #333333; } .search_hover { background-color:#EBEBEB!important; color:#232323!important; } body { padding: 50px; text-align: center; background-color: #FFFFFF; font-family: Geneva, Arial, Helvetica, sans-serif; font-size: 13px; } body a { text-decoration: none; } #s { outline:none; width: 480px; padding: 10px; border: 1px solid #CCCCCC; color: #CCCCCC; z-index: 200; position: relative; height: auto; } .go { padding: 9px; font-weight: bold; width: 60px; margin-left: -4px; border: 0px solid #CCCCCC; height: auto; font-size: 16px; background-color: #F7F7F7; } h1 { font-family: Georgia, "Times New Roman", Times, serif; padding: 0px; margin-bottom: 10px; font-size: 30px; color: #333333; } h2 { font-family: Georgia, "Times New Roman", Times, serif; padding: 0px; font-size: 12px; color: #999999; margin: 0px; font-style: italic; font-weight: normal; } now i just want to edit one thing, when you search for something, results are shown under the search field, when you click on each result, goes to a link. i want when clicking on a result, not going to link, just show that result string on the search field. could you please tell how to do it? where should i edit in script? thanks in advanced Hey folks, Forgive me in advance if this is not the correct place to post this thread. I am a new member to this forum and need a little assistance. I have some script to create a quiz but need a little more detail. Does anyone know some code I can insert, and where to randomize the questions. Secondly if I have a test bank of 100 questions but want to limit the test to 20 questions what code would I need to insert that as well. Any assistance is very much appreciated. thank you. kenster Hey I was wondering, I have a box with tabs at the bottom. As you click the tabs, different stories appear in the box. However, I have the box in a fixed length. So if stories are longer, then they disappear beneath the visible line of the box. When I had it auto-adjusting though, the box would change based on the story I was clicking on. It gets weird. Is there a way to have the box auto-adjust based on the largest amount of text and have it stay that height regardless on what story you pick? I hope this makes sense. Thanks! KZ This is my code from prelim to finals. The missing part here is when the input is less than or equal to 65 and greater than 100, the prompt will say INVALID ENTRY. However, after it says Invalid Entry, it must ask you to enter again an Entry until you input a valid entry. It must be terminated after you input from prelim to finals either 0,20,30,40 or after you input a valid entry and after the program calculated it. My program does not terminate after I input valid entries. It just continue to ask grade again and again even it already calculated the grades. I don't know how will I put those code inside the program. I'm getting really confused. Code: <html> <head> <title>Web Programming Laboratory Exam</title> </head> <body> <script language="JavaScript"> do { { var pg=prompt('Enter Prelim Grade','0'); if(pg==0) { alert('No Grade'); document.write('<br>Prelim Grade is '+pg); } else if(pg==20) { alert('Not Attending'); document.write('<br>Prelim Grade is '+pg); } else if(pg==30) { alert('Dropped'); document.write('<br>Prelim Grade is '+pg); } else if(pg==40) { alert('Incomplete'); document.write('<br>Prelim Grade is '+pg); } else document.write('Prelim Grade is '+pg); var mg=prompt('Enter Midterm Grade','0'); } { if(mg==0) { alert('No Grade'); document.write('<br>Midterm Grade is '+mg); } else if(mg==20) { alert('Not Attending'); document.write('<br>Midterm Grade is '+mg); } else if(mg==30) { alert('Dropped'); document.write('<br>Midterm Grade is '+mg); } else if(mg==40) { alert('Incomplete'); document.write('<br>Midterm Grade is '+mg); } else document.write('</br>Midterm Grade is '+mg); var fg=prompt('Enter Final Grade','0'); } { if(fg==0) { alert('No Grade'); document.write('<br>Final Grade is '+fg); } else if(fg==20) { alert('Not Attending'); document.write('<br>Final Grade is '+fg); } else if(fg==30) { alert('Dropped'); document.write('<br>Final Grade is '+fg); } else if(fg==40) { alert('Incomplete'); document.write('<br>Final Grade is '+fg); } else { document.write('</br>Final Grade is '+fg); sg=((pg*.3)+(mg*.3)+(fg*.4)); document.write('<br>Your Semestral Grade is '+sg); } } if (sg>=74.5) { document.write('<br>Remarks: Passed'); document.write('</br>This Program is developed by -k3nN'); } else if (sg<74.5) { document.write('<br>Remarks:Failed'); document.write('</br>This Program is developed by -k3nN'); } } while (sg>=74.5|sg<74.5) { document.write('</br>Thanks') } </script> </body> </html> I have an assignment to create a program in JS but I have not read JS much more. So, for this assignment, can anyone help me to solve this assignment? Check attachment. Uploaded with ImageShack.us Hello everyone. This is my first program. According to the idea of a program that calculates the sum of savings with the bank interest rates that is paid each year. And I put one amount every month. The question is very simple why full = 0? Code: var years = prompt("How many years will accumulate?)"); var prec = prompt("And how many % bank give?"); var income = prompt("How many you will put off in bank?"); var num = 12; var full = 0; months=years*num; console.log("Altogether we get " + years + " years and " + months + " months.") for (var month = 0; month == months; month++) { if (month % num == 0) { full = full + income + (full*prec/100); } else { full = full + income; } } console.log("Total accumulated =" + full); Reply With Quote 01-24-2015, 04:37 PM #2 leonfresh View Profile View Forum Posts New to the CF scene Join Date Jan 2015 Posts 8 Thanks 0 Thanked 0 Times in 0 Posts var full = 0 declares the variable as an integer variable. it's important to do so to avoid declaration errors. Reply With Quote 01-24-2015, 05:09 PM #3 jmrker View Profile View Forum Posts Senior Coder Join Date Aug 2006 Location FL Posts 3,175 Thanks 39 Thanked 510 Times in 504 Posts You have a logic problem. Try... Code: for (var month = 0; month<months; month++) { Also note that your logic applies the full percentage at the 1st month of the loan/deposit. Is this what your really intended? Reply With Quote Users who have thanked jmrker for this post: Nadir+ (01-24-2015) 01-24-2015, 06:28 PM #4 Nadir+ View Profile View Forum Posts New to the CF scene Join Date Jan 2015 Posts 6 Thanks 1 Thanked 0 Times in 0 Posts i catch another problem, when i change this Code: for (var month = 0; month == months; month++) { on this, Code: for (var month = 0; month<months; month++) { program started work. But in rusults see this . Code: Altogether we get 1 years and 12 months. Total accumulated =01000100100100100100100100100100100100 all code there Code: var years = prompt("How many years will accumulate?)"); var prec = prompt("And how many % bank give?"); var income = prompt("How many you will put off in bank?"); var num = 12; var full = 0; months=years*num; console.log("Altogether we get " + years + " years and " + months + " months.") for (var month = 0; month < months; month++) { if (month % num == 0) { full = full + income + (full*prec/100); } else { full = full + income; } } console.log("Total accumulated =" + full); Reply With Quote 01-24-2015, 06:39 PM #5 Nadir+ View Profile View Forum Posts New to the CF scene Join Date Jan 2015 Posts 6 Thanks 1 Thanked 0 Times in 0 Posts i realized something if i delete var income and just put in its place 100, program work almost normal. Code: Altogether we get 2 years and 24 months. main.js:17 Total accumulated =2520 But if i write 1 year it dont work,how can i fix it? Code: Altogether we get 1 years and 12 months. main.js:17 Total accumulated =1200 Reply With Quote 01-24-2015, 09:42 PM #6 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,310 Thanks 82 Thanked 4,754 Times in 4,716 Posts The value you get from a call to prompt() is *ALWAYS* a string. When you use the + operator with a string, it does *NOT* do addition; it does string concatenation. You just need to convert all those prompt() results to numbers: Code: var years = Number( prompt("How many years will accumulate?") ); var prec = Number( prompt("And how many % bank give?") ); var income = Number( prompt("How many you will put off in bank?") ); Also, you need to do Code: for (var month = 0; month <= months; month++) { else you will only do (for example) up to month 23 when the user asks for 2 years. Be aware that prompt() and confirm() and console.log() are considered VERY obsolete and should only be used for debugging purposes, not for real web code. I need a count down clock that will count down 18 minutes and reset itself at the end. also i need a counter that increases by +1 every 18 minutes starting at 0. thankyou Im writing this code for a gas station program. I have been writing and improving my code for about 3 weeks now and its quite long. I have about classes , customer class, office class and a gas pumps classes. I need help on how to get started on finding the total output at the end of the day. Conceptually i know what i have to do but I don't know where to begin writing the code. I think each time there is a new customer i should add the amount of fuel purchased to a new total fuel purchases variable in the gas pump class. If any one could give me some advice or tips on my theory it would be great ! Should I create a method or can i be done without one. Code: import java.util.Random; import java.util.Scanner; public class Customer { private String carTag; private double gasPurchased; private int gasType; public Customer () { Random gen = new Random ( ); carTag = ""; for (int i = 1; i <= 6; i++) { //a random number between 48 and 90 int code = gen.nextInt (43)+ 48; if ((code <= 64) && (code >= 58)) { i--; continue; } carTag += ((char)(code)); } System.out.println ("a car arrives; tag number:" + carTag); } public int getGasType () { Scanner inputDevice = new Scanner (System.in); //1:regular, 2:plus, 3:premium System.out.println ("enter type of gas to buy " + "(1:regular, 2:plus, 3:premium): "); gasType = inputDevice.nextInt (); return gasType; } public double getGasPurchased () { Random gen = new Random (); gasPurchased = gen.nextDouble ()* 50; return gasPurchased; } public String getCarTag () { return carTag; } Code: import java.util.Random; public class Office { public static void main (String [ ] args) { double regularTank = 1000; double plusTank = 1000; double primiumTank = 1000; GasPump pump1 = new GasPump ( ); GasPump2 pump2 = new GasPump2 ( ); Random gen = new Random (); //asuumint gas tanks always have gas, will upgrade later do { int whatHappens = gen.nextInt (100); if (whatHappens == 5) { System.out.println ("gas station closed"); break; } else if ((whatHappens % 10) == 0) { if (pump1.pumpAvailable ()) pump1.customerArrival (); else System.out.println ("a new customer arrives at pump 1, but is turned away, gas pump is busy"); } else { if (pump1.pumpAvailable ()) System.out.println ("no customer; waiting........."); } if (!pump1.pumpAvailable()) { if (pump1.updateClock () == 0) pump1.saleComplete (); } } while (true); do system.exit () Code: public class GasPump { final private double REGULAR_PRICE = 3.15; final private double PLUS_PRICE = 3.5; final private double PREMIUM_PRICE = 4.5; final private double HOSE_FLOW_RATE = 0.85; private double totalPayment; private Customer who; private int timeLeftToFinish; private int gasType; private double gasPurchased; private String carTag; public GasPump () { who = null; totalPayment = 0; timeLeftToFinish = 0; } public void customerArrival () { who = new Customer (); System.out.println ("welcome to jack's gas station PUMP 1 "); gasType = who.getGasType (); gasPurchased = who.getGasPurchased (); timeLeftToFinish = (int)(gasPurchased/HOSE_FLOW_RATE); System.out.println (timeLeftToFinish + " total time units needed for this transaction..."); carTag = who.getCarTag (); } private void printReceipt ( ) { System.out.println ("****Sale Receipt"); switch (gasType) { case 1: System.out.println ("regular gas"); break; case 2: System.out.println ("plus gas"); break; case 3: System.out.println ("premium gas"); break; } System.out.println ("gas amount: " + gasPurchased + "\ntotal payment" + totalPayment + "\nthank you"); System.out.println("Pump has " + regularTank()); } private void resetPump ( ) { who = null; totalPayment = 0; timeLeftToFinish = 0; } public int updateClock () { timeLeftToFinish--; System.out.println (timeLeftToFinish + " time units left to finish "); return timeLeftToFinish; } public void saleComplete ( ) { switch (gasType) { case 1: totalPayment = REGULAR_PRICE * gasPurchased; break; case 2: totalPayment = PLUS_PRICE * gasPurchased; break; case 3: totalPayment = PREMIUM_PRICE * gasPurchased; break; } printReceipt ( ); resetPump ( ); } public boolean pumpAvailable () { return (who == null); } } 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> 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> Im trying to write a program that determines if an array is Ragged or not. I'm fairly new to writing programs in javascript and need a little help with this program. So far I have the following and need to write the program aspect for it. Thanks for taking a look for me. Code: document.writenln("Ragged or not<br />") if (raggedOr(a)) document.writenln("Array is Ragged"); else document.writenln("Array is not Ragged"); raggedOr was going to be the name of the function. Basically i have an image of a ball that i am trying to make bounce from top to bottom so far it is just going to the bottom and stopping plz help thanks <head> <title></title> </head> <body> <center> <input type="button" value="Click" onClick="moveDown()"/> </center> <img id="Ball" src="ball.jpg" style="position:absolute; top:100px; left:100px;"/> <script language="JavaScript"> var Image = document.getElementById("Ball"); var Position = 100; var direction = 1; function moveDown() { if(direction > 0) { Image.style.top = parseInt(Image.style.top) + 20+'px'; } if(parseInt(Image.style.top)> 100 || direction > 1 ) direction = 1 if(parseInt(Image.style.top)> 500 || direction < 1 ) { direction = -1 Image.style.top = parseInt(Image.style.top) - 20+'px'; } } setInterval ("moveDown()", 50 ); </script> </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 wrote about this script a couple weeks ago. I stopped working on it, and just got on it today. Question, what's the easiest way to have it so Monday, tuesday, Wednesday, etc and then the total amount of hours gets added. Code: <html> <head> <script language="JavaScript" src="gen_validatorv5-.js" type="text/javascript" xml:space="preserve"></script> <script type="text/javascript"> function calc(nForm){ var inHour =parseInt( nForm.inHr.value) var inMinutes = parseInt( nForm.inMin.value); var lunchOutHour = parseInt(nForm.lunchOutHr.value); var lunchOutMinutes = parseInt( nForm.lunchOutMin.value); var lunchInHour = parseInt( nForm.lunchInHr.value); var lunchInMinutes = parseInt( nForm.lunchInMin.value); var outHour = parseInt( nForm.outHr.value); var outMinutes = parseInt( nForm.outMin.value); var linearInTime = 60*(inHour)+(inMinutes); var linearLunchOutTime = 60*(lunchOutHour)+(lunchOutMinutes); var linearLunchInTime = 60*(lunchInHour)+(lunchInMinutes); var linearOutTime = 60*(outHour)+(outMinutes); var workDay = linearOutTime-linearInTime; var lunchPeriod = linearLunchInTime-linearLunchOutTime; var linearMinutesWorked = workDay-lunchPeriod; var hoursWorked = parseInt(linearMinutesWorked/60); var minutesWorked = linearMinutesWorked-(hoursWorked*60) if (hoursWorked < 10){hoursWorked = "0"+hoursWorked} if (minutesWorked < 10){minutesWorked = "0"+minutesWorked} nForm.timeWorked.value = hoursWorked+":"+minutesWorked; } </script> </head> <body> <div align="center"> <h1> <script src='scripts/gen_validatorv5.js' type='text/javascript'></script> <script src='scripts/sfm_moveable_popup.js' type='text/javascript'></script> <style type='text/css'> .error_strings { font-family:Verdana; font-size:10px; color:#660000; } .sfm_float_error_box { position:absolute; z-index:999; cursor:default; font-family:Verdana; font-size:10px; color:#660000; background-color:#ffff66; border-style:solid; border-width:1px; border-color:#660000; } .sfm_float_box_td { padding:3px; cursor:default; font-family:Verdana; font-size:10px; color:#660000; background-color:#ffff66; } .sfm_close_box { font-family:Verdana; font-size:10px; font-weight:bold; color:#ffffff; background-color:#660000; border-width:0px; text-align:center; } .sfm_cr_box { font-family:Verdana; font-size:10px; color:#888888; border-style:solid; border-width:0px; border-color:#660000; } .sfm_cr_box a { color:#888888; } </style> Masquerade Timesheet Entry</h1> </div> <div id='timeSheet_errorloc' class='error_strings' style=''></div> <form name='timeSheet'> <table width="833" height="244" border="1" align="center"> <tr> <td width="266"><p align="left">Monday :</p> Clock In: <label> <input name="inHr" type="text" id="inHr" size="10" maxlength="2"> </label>   <label> <input name="inMin" type="text" id="inMin" size="10" maxlength="2"> </label> <br> Lunch Out: <label> <input name="lunchOutHr" type="text" id="lunchOutHr" size="10" maxlength="2"> </label>   <label></label> <input name="lunchOutMin" type="text" id="lunchOutMin" size="10" maxlength="2"> <br> Lunch In: <label> <input name="lunchInHr" type="text" id="lunchInHr" size="10" maxlength="2"> </label>   <label> <input name="lunchInMin" type="text" id="lunchInMin" size="10" maxlength="2"> </label> <br> Clock Out: <label> <input name="outHr" type="text" id="outHr" size="10" maxlength="2"> </label>   <label> <input name="outMin" type="text" id="outMin" size="10" maxlength="2"> </label> <p>Time Worked: <input type='text' name='timeWorked' size='5' readonly> </p></td> <td width="269"><p>Tuesday:</p> <p>Clock In: <label> <input name="inHr2" type="text" id="inHr2" size="10" maxlength="2"> </label>   <label> <input name="inMin2" type="text" id="inMin2" size="10" maxlength="2"> </label> <br> Lunch Out: <label> <input name="lunchOutHr2" type="text" id="lunchOutHr2" size="10" maxlength="2"> </label>   <label></label> <input name="lunchOutMin2" type="text" id="lunchOutMin2" size="10" maxlength="2"> <br> Lunch In: <label> <input name="lunchInHr2" type="text" id="lunchInHr2" size="10" maxlength="2"> </label>   <label> <input name="lunchInMin2" type="text" id="lunchInMin2" size="10" maxlength="2"> </label> <br> Clock Out: <label> <input name="outHr2" type="text" id="outHr2" size="10" maxlength="2"> </label>   <label> <input name="outMin2" type="text" id="outMin2" size="10" maxlength="2"> </label> </p> <p>Time Worked: <input type='text' name='timeWorked2' size='5' readonly> </p></td> <td width="276"><p>Wednesday:</p> <p>Clock In: <label> <input name="inHr3" type="text" id="inHr3" size="10" maxlength="2"> </label>   <label> <input name="inMin3" type="text" id="inMin3" size="10" maxlength="2"> </label> <br> Lunch Out: <label> <input name="lunchOutHr3" type="text" id="lunchOutHr3" size="10" maxlength="2"> </label>   <label></label> <input name="lunchOutMin3" type="text" id="lunchOutMin3" size="10" maxlength="2"> <br> Lunch In: <label> <input name="lunchInHr3" type="text" id="lunchInHr3" size="10" maxlength="2"> </label>   <label> <input name="lunchInMin3" type="text" id="lunchInMin3" size="10" maxlength="2"> </label> <br> Clock Out: <label> <input name="outHr3" type="text" id="outHr3" size="10" maxlength="2"> </label>   <label> <input name="outMin3" type="text" id="outMin3" size="10" maxlength="2"> </label> </p> <p>Time Worked: <input type='text' name='timeWorked3' size='5' readonly> </p></td> </tr> <tr> <td><p>Thursday:</p> <p>Clock In: <label> <input name="inHr4" type="text" id="inHr4" size="10" maxlength="2"> </label>   <label> <input name="inMin4" type="text" id="inMin4" size="10" maxlength="2"> </label> <br> Lunch Out: <label> <input name="lunchOutHr4" type="text" id="lunchOutHr4" size="10" maxlength="2"> </label>   <label></label> <input name="lunchOutMin4" type="text" id="lunchOutMin4" size="10" maxlength="2"> <br> Lunch In: <label> <input name="lunchInHr4" type="text" id="lunchInHr4" size="10" maxlength="2"> </label>   <label> <input name="lunchInMin4" type="text" id="lunchInMin4" size="10" maxlength="2"> </label> <br> Clock Out: <label> <input name="outHr4" type="text" id="outHr4" size="10" maxlength="2"> </label>   <label> <input name="outMin4" type="text" id="outMin4" size="10" maxlength="2"> </label> </p> <p>Time Worked: <input type='text' name='timeWorked4' size='5' readonly> </p></td> <td><p>Friday:</p> <p>Clock In: <label> <input name="inHr5" type="text" id="inHr5" size="10" maxlength="2"> </label>   <label> <input name="inMin5" type="text" id="inMin5" size="10" maxlength="2"> </label> <br> Lunch Out: <label> <input name="lunchOutHr5" type="text" id="lunchOutHr5" size="10" maxlength="2"> </label>   <label></label> <input name="lunchOutMin5" type="text" id="lunchOutMin5" size="10" maxlength="2"> <br> Lunch In: <label> <input name="lunchInHr5" type="text" id="lunchInHr5" size="10" maxlength="2"> </label>   <label> <input name="lunchInMin5" type="text" id="lunchInMin5" size="10" maxlength="2"> </label> <br> Clock Out: <label> <input name="outHr5" type="text" id="outHr5" size="10" maxlength="2"> </label>   <label> <input name="outMin5" type="text" id="outMin5" size="10" maxlength="2"> </label> </p> <p>Time Worked: <input type='text' name='timeWorked5' size='5' readonly> </p></td> <td><div align="left"> <p> <input type='button' value="Calculate" onClick="calc(this.form)"> <input type="button" name="reset_form" value="Clear Forms" onClick="this.form.reset();"> </p> <p>Total Time Worked: <input type="text" name="totalhr" id="totalhr"> </p> <label></label> </div></td> </tr> </table> <p align="left"> </P> <p align="left"> </P> <p align="left"> </P> <p align="left"> </P> <p><br> <br> <br> <br> </p> </form ><p> </p> <p> </p> </body> </html> <script type="text/javascript"> var myString = "zero one two three four"; var mySplitResult = myString.split(" "); for(i = 0; i < mySplitResult.length; i++){ document.write("<br /> Element " + i + " = " + mySplitResult[i]); } </script> "split" function splits the string whenever it encounters "space". But please explain me how the strings are stored in "mySplitResult". And can we use Arrays for this program? If so, can you code it. Thanks in advance! |