JavaScript - Want Text Red When Counter Is Negative, Green When Positive
I'm just starting out learning and have sort of given myself a couple of basic problems to solve. I pretty quickly found something that's apparently hard to Google.
I've made a page that shows a counter number, starting at 0, with buttons that will increase or decrease the number by 1 or 10. So I'd like to figure out how to show that number in red when it is a negative number and in green when it is a positive number. I've tried a couple of things, including an if... else, but here's my latest crack: Code: var counter=0; function countUp() { lastCounter=counter; counter++; display(); } function countDown() { lastCounter=counter; counter--; display(); } function tenUp() { lastCounter=counter; counter+=10; display(); } function tenDown() { lastCounter=counter; counter-=10; display(); } function lastNumber() { counter=lastCounter document.getElementById("number").innerHTML=lastCounter; } function display () { number=counter+''; switch(counter) { case counter== 0; document.getElementById("number").innerHTML=number.fontcolor(white); break; case counter> 0; document.getElementById("number").innerHTML=number.fontcolor(green); break; case counter< 0; document.getElementById("number").innerHTML=number.fontcolor(red); break; } //end switch } //end display I suspect that what I'm doing totally wrong has to do with how I'm describing the case or with calling one function inside another function, since it works up until I start messing with that (had the document.getElementByID stuff in the countUp, countDown, etc., functions before) but I don't know. Thanks in advance for any help you can offer. Similar TutorialsHi, I have the below code it works, but there a problem. If you press return to drop a line it counts that as a letter/number. Is there a way to fix it? <html> <head> <title></title> </head> <body> <script language="JavaScript"> function CheckCount() { var maxChar = 2000000; if(document.frmMain.txtDetail.value.length > maxChar) { return false; } else { document.frmMain.txtCount.value = document.frmMain.txtDetail.value.length; } } </script> <body> <form name="frmMain" method="post"> <textarea name="txtDetail" cols="40" rows="5" id="txtDetail" onKeyUp="return CheckCount()"></textarea> <br> <input name="txtCount" type="text" id="txtCount" style="width:65px;" value="0"> </form> </body> </html> Hi everybody I would like to be able to make it so that an order form only submits positive results. I have modified this form http://www.mcfedries.com/JavaScript/OrderTotals.asp for my friends website. She has 50 different products that she makes (different sizes and colors). The form submits results for things ordered but also for things not ordered. PROD_yellow_3.00= PROD_green_3.00= PROD_blue_3.00= PROD_red_3.00=1 PROD_purple_3.00= As you can see the only thing ordered is the $3.00 red product. But all the other ones not ordered show up in the form results. Is there a way to only send results of items actually ordered? I have looked at other order forms and they also send all results not just positive ones. Thank you. My javascript experience: none, only able to modify things. (And I wanted to ask this question on the site that has the sample order form but something wasn't working and I couldn't join.) I've set up a mock registration form page so I can learn a bit about javascript's form validation. (newbie) I want to try to attempt to style the border of a form field green when the user enters the correct info into the form text field and red on all other fields if the user doesnt enter any info into them. When i test it, enter the right info into the username field, leave the others blank, and hit the submit button it styles the username field green ok but it doesnt make the next fields (password and so on) red. Could someone please explain what I am doing wrong? here is my code so far... Note: just for testing purposes I've put return false on everything so it displays a message when everythings ok. Code: .... <script type="text/javascript"> window.onload = function() { document.forms[0].username.focus(); } function validate(form) { var form = document.getElementById("reg"); var e = document.getElementById("error"); e.style.background = "red"; for(var i = 0; i < form.elements.length; i++) { var el = form.elements[i]; if(el.type == "text" || el.type == "password") { if(el.value == "") { e.innerHTML = "Please fill in all fields!"; el.style.border = "1px solid red"; el.focus(); return false; } else { el.style.border = "1px solid green"; return false; } } } var un = form.username; un.value = un.value.replace(/^\s+|\s+$/g,""); if((un.value.length < 3)|| (/[^a-z0-9\_]/gi.test(un.value))) { e.innerHTML = "Only letters,numbers and the underscore are allowed (no spaces) - 3-16 characters"; un.focus(); return false; } var pw = form.password; pw.value = pw.value.replace(/^\s+|\s+$/g,""); if((pw.value.length < 3) || (/[^a-z0-9]/gi.test(pw.value))) { e.innerHTML = "Only letters and numbers are allowed (no spaces) - 3-16 characters"; pw.focus(); return false; } e.innerHTML = "You filled in all the fields, well done!"; e.style.background = "green"; return false; } </script> </head> <body> <div id="wrapper"> <div id="header"> <h1>My Cool Website</h1> </div> <div id="content"> <div class="padding"> <h2>Registration</h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus. Vivamus ut sem. Fusce aliquam nunc vitae purus. Aenean viverra malesuada libero. Fusce ac quam. Donec neque. Nunc venenatis enim nec quam. Cras faucibus, justo vel accumsan aliquam, tellus dui fringilla quam, in condimentum augue lorem non tellus. Pellentesque id arcu non sem placerat iaculis. Curabitur posuere, pede vitae lacinia accumsan, enim nibh elementum orci, ut volutpat eros sapien nec sapien. Suspendisse neque arcu, ultrices commodo, pellentesque sit amet, ultricies ut, ipsum. Mauris et eros eget erat dapibus mollis. Mauris laoreet posuere odio. Nam ipsum ligula, ullamcorper eu, fringilla at, lacinia ut, augue. Nullam nunc.</p> <form id="reg" action="#" method="post" onsubmit="return validate(this)"> <div id="error"></div> <div><label for="username">Username</label></div> <div><input type="text" name="username" id="username" size="30" maxlength="16" /></div> <div><label for="password">Password</label></div> <div><input type="password" name="password" id="password" size="30" maxlength="16" /></div> <div><label for="c_password">Confirm Password</label></div> <div><input type="password" name="c_password" id="c_password" size="30" maxlength="16" /></div> <div><label for="email">Email address</label></div> <div><input type="text" name="email" id="email" size="30" maxlength="200" /></div> <div><label for="c_email">Confirm Email address</label></div> <div><input type="text" name="c_email" id="c_email" size="30" maxlength="200" /></div> <div><label for="firstname">First name</label></div> <div><input type="text" name="firstname" id="firstname" size="30" maxlength="100" /></div> <div><label for="surname">Surname</label></div> <div><input type="text" name="surname" id="surname" size="30" maxlength="100" /></div> <div><label for="gender">Gender</label></div> <div> <div><input type="radio" name="gender" id="gender" value="m" checked="checked" />Male</div> <div><input type="radio" name="gender" value="f" />Female</div> </div> <div><input type="submit" value="Register" name="submit" /></div> </form> </div> </div> <div id="footer"> <p>Copyright © 2009 My Cool Website</p> </div> </div> </body> </html> I am using Code: var number = -141; later on when i use the variable number in another calculation, for example Code: var result = 450 + number; I get the result NaN. How can i rectify this? Thanks If a negative number is entered into the reading variable it should be displayed as a zero. This works with the first calculations such as average but right at they very end the the alert wont display the highest average it just displays the one which has a negative number typed in to it. Code: var region=0 var reading=0 var average=0 var count=0 var readingSum=0 var catergory=0 var dry=0 var normal=0 var wet=0 var countWet=0 var countNormal=0 var countDry=0 var totalLoop=0 var numLocations=0 var maxAverage=0 var maxRegion=0 var maxReadings=0 var totalReadings=0 // ** Find out how many locations ** // numLocations=eval(prompt("How many locations are you taking readings for?")); // ** Loop for multiple entries ** // for(totalLoop=1; totalLoop<=numLocations; totalLoop=totalLoop+1) { // ** Reset total for loop ** // readingSum=0 // ** Get Region ** // region = prompt("Enter region please"); // ** Get Readings ** // totalReadings = eval(prompt("Enter readings please")); // ** Get readings and Prevent negative number ** // if(totalReadings<=0) { alert("Please enter valid reading") } else { alert("You entered " + totalReadings); } // ** Ask for indivdual readings ** // for(count=1; count<=totalReadings; count=count+1) { reading=eval(prompt("Enter reading please")); // ** Prevent negative number ** // if(reading<0) { reading=0 alert("Please enter valid reading") } // ** Work out Total of readings ** // readingSum= readingSum + reading } // ** Work out average ** // average= readingSum/totalReadings // ** Put average into a category and display everything ** // if(average<5) { catergory="dry" countDry=countDry+1 } else if(average>=5 && average<20) { catergory="normal" countNormal= countNormal+1 } else if(average>20) { catergory="wet" countWet=countWet+1 } alert("Location is " + region + "\nNumber of weakly readings taken is " + totalReadings + "\nTotal of readings is " + readingSum + "\nAverage is " + average + "\nLocation is " + catergory); // ** Find Highest average ** // if((average>maxAverage) || (totalReadings>maxReadings)) { maxAverage=average maxRegion=region } } // ** Final Report ** // alert("Number of locations is " + numLocations + "\nDry is " + countDry + "\nNormal is " + countNormal + "\nWet is " + countWet + "\nLocation with highest average reading is " + maxRegion + "\nHighest average is " + maxAverage); Do i need a while loop? i am only allowed to use while, for and if statements I need help with a counter that will either display a different image everyweek or change text every week. The scenario is a counter will be on the top right corner of the page, and every week the number will change from 1 to 2 to 3... to 52... I searched on this forum for answers, i found some similar for a different day counter. Any help would be great! Hey Everyone, I'm working on a counter. I have two images - each with their own click count. Right now each time the page loads the counter goes back to zero. I would assume I need some kind of server side coding. Any recommendations? Here's what I have so far. <html> <head> <script type="text/javascript"> var counter = 0; function increaseloveit() { counter += 1; document.getElementById('loveit').value = counter; } var counter = 0; function increasehateit() { counter += 1; document.getElementById('hateit').value = counter; } </script> </head> <body> <form> <a href="#" onclick="javascript:increaseloveit();"><input type="button" value="Love It!" name="loveit" onclick="" /></a><input id="loveit" value="0" size="2" /></form> <form> <a href="#" onclick="javascript:increasehateit();"><input type="button" value="Hate It!" name="hateit" onclick="" /></a><input id="hateit" value="0" size="2" /></form> </body> </html> I have the following codes and it seems to work well but when exiting the site and re-entering it resets the values to 0 again. I am not sure how to proceed with this, been considering cookies but what if the user clears there cookies, I then looked at PHP but not understanding that to well at this stage. Javascript Code: // Function to count clicks on links var clicks1 = 0; var clicks2 = 0; var clicks3 = 0; var clicks4 = 0; function link1(){ document.getElementById('clicked1').value = ++clicks1; } function link2(){ document.getElementById('clicked2').value = ++clicks2; } function link3(){ document.getElementById('clicked3').value = ++clicks3; } function link4(){ document.getElementById('clicked4').value = ++clicks4; } HTML Code: Code: <tr valign="middle" align="center"><td colspan="1"><a target="_blank" href="http://mistiquestormelectronics.webs.com/" onclick="link1()"><img src="site_graphics/reinet.jpg" alt="Mistique Storm" width="120" height="90" /></a></td> <td colspan="2" align="left"><p>For all your Electronic equipment needs.</p></td> <td colspan="1" width="8%"><input id="clicked1" style="color: #000000; font-weight:bold; border-style: none; font-family: arial; background-color: #00FF00; text-align: center;" readonly="readonly" size="10" onfocus="this.blur();" value="0" ></td></tr> Any ideas, suggestions. Please Help? So I'm really new to javascript and html. The most advanced thing Ive made was probably a Russian rullete simulator, but I need help with this one program Im working on. So if anyone could tell me whats wrong with this, I would appreciate it! <html> <head> <font size="4">Click the button below as many times as you can</font> <br> <script type="text/javascript"> var clicks=0 function count() { clicks=clicks+1; } </script> </head> <body> <input type="button" value="Click Me" OnClick="count()"> <br> <p>Clicks: <script type="text/javascript"> document.write(clicks); </script></p> </body> </html> I am trying to use the Jquery loader (this ends when page loads) but I want it to load how many seconds the page took. (using the clean preloader) $( "#progressbar" ).progressbar({ value: setTimeout("seconds++",10000000) }); but getting "anything" to work in the "VALUE" has been such a pain. any one that knows how to create a timer to add to the value so that preload will keep loading? or if even possible? thanks Hi All, could you please help me. A have a little program and i need to count somehow how many times a while loop is ran. how could i do that? Thanks for your help H, I'm trying to create an sms form. but I want the users to be able to monitor the characters and sms number as they type...taking 160 characters to be 1 page. pls I'll need help with coding this form to display characters left in 'ch_count' box and number of pages in the 'pages' box while typing in the 'message' textarea....hope it's clear enough...thanks Code: <p> <textarea name="message" cols="" rows="" id="message"></textarea> </p> <p> <input name="ch_count" type="text" id="ch_count" size="8" /> characters left <input name="pages" type="text" id="pages" size="8" /> pages </p> Anybody help to start out this code: Create a "nag" counter that tells users to register. Save the counter in a cookie and display a message reminding users to register every fifth time they visit your site. There are four other parts to this task that I know how to do. I cannot find anything close to this in our book referencing a nag-counter or something similar to it. Thanks, in advance. Regards, AO5431 Hi, I have added a time counter in below code. This is used to track the total time of a project. If a person is going on break, then they will apply the break that stops the time counter. However, once they come back from break and end the break, then time is counting at double speed (two seconds instead at one second). Is there any mistake that I done that made the time counter to increment by 2 seconds instead of 1 second after break. Any help please.... Code: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <title>Strategy One - Tracker</title> <link rel="stylesheet" href="style.css" type="text/css" media="screen" /> <!--[if IE 6]><link rel="stylesheet" href="style.ie6.css" type="text/css" media="screen" /><![endif]--> <!--[if IE 7]><link rel="stylesheet" href="style.ie7.css" type="text/css" media="screen" /><![endif]--> <!-- Script for Current time in text box --> <script type="text/javascript"> function GetDate() { var curDateTime = new Date() var curHour = curDateTime.getHours() var curMin = curDateTime.getMinutes() if(curHour<10) curHour = "0" + curHour if(curMin<10) curMin = "0" + curMin document.getElementById('start_time').value = curHour + ":" + curMin; var row = document.getElementById("end1_time"); var row1 = document.getElementById("start1_time"); row.style.display = 'none'; row1.style.display = 'none'; } </script> <!-- End of Script for Current time in text box --> <!-- Script for Current time in text box --> <script type="text/javascript"> function GetDate1() { var curDateTime = new Date() var curHour = curDateTime.getHours() var curMin = curDateTime.getMinutes() if(curHour<10) curHour = "0" + curHour if(curMin<10) curMin = "0" + curMin document.getElementById('end_time').value = curHour + ":" + curMin; var row = document.getElementById("start1_time"); var row1 = document.getElementById("end1_time"); var row2 = document.getElementById("start2_time"); var row3 = document.getElementById("end2_time"); row.style.display = 'none'; row1.style.display = 'none'; row2.style.display = 'none'; row3.style.display = 'none'; } </script> <script type="text/javascript"> function GetDate2() { var curDateTime = new Date() var curHour = curDateTime.getHours() var curMin = curDateTime.getMinutes() if(curHour<10) curHour = "0" + curHour if(curMin<10) curMin = "0" + curMin document.getElementById('break_time_out').value = curHour + ":" + curMin ; var row = document.getElementById("end2_time"); row.style.display = ''; } </script> <script type="text/javascript"> function GetDate3() { var curDateTime = new Date() var curHour = curDateTime.getHours() var curMin = curDateTime.getMinutes() if(curHour<10) curHour = "0" + curHour if(curMin<10) curMin = "0" + curMin document.getElementById('break_time_in').value = curHour + ":" + curMin ; } </script> <script type="text/javascript"> function tout1() { var temp= document.tracker.start_time.value; if(temp.length>0) { var row1 = document.getElementById("end1_time"); var row2 = document.getElementById("start2_time"); row1.style.display = 'none'; row2.style.display = 'none'; } else { var row = document.getElementById("start1_time"); var row1 = document.getElementById("end1_time"); var row2 = document.getElementById("start2_time"); row.style.display = 'none'; row1.style.display = 'none'; row2.style.display = 'none'; } } function tout2() { var temp= document.tracker.start_time.value; if(temp.length>0) { var row = document.getElementById("start1_time"); var row1 = document.getElementById("end1_time"); var row2 = document.getElementById("start2_time"); var row3 = document.getElementById("end2_time"); row.style.display = 'none'; row1.style.display = 'none'; row2.style.display = 'none'; row3.style.display = 'none'; } else { var row = document.getElementById("start1_time"); var row1 = document.getElementById("end1_time"); var row2 = document.getElementById("start2_time"); var row3 = document.getElementById("end2_time"); row.style.display = ''; row1.style.display = 'none'; row2.style.display = 'none'; row3.style.display = 'none'; } } </script> <script type="text/javascript"> var seconds = 0; var minutes = 0; var hours = 0; function zeroPad(time) { var numZeropad = time + ''; while(numZeropad.length < 2) { numZeropad = "0" + numZeropad; } return numZeropad; } function countSecs() { var j=document.tracker.hide.value; if(j=="yes") { seconds++; if (seconds > 59) { minutes++; seconds = 0; } if (minutes > 59) { hours++ minutes = 0; } document.tracker.time_utilization.value = zeroPad(hours) + ":" + zeroPad(minutes) + ":" + zeroPad(seconds); } else {} } function startTimer() { action = window.setInterval(countSecs,1000); } function s() { document.tracker.hide.value ="yes"; startTimer(); } function p() { document.tracker.hide.value ="no"; } </script> </head> <body> <form name="tracker" method="post" action="processor.php" onsubmit="return formCheck(this);"> <label class="formFieldQuestion">Start Time *</label><input readonly class=mainForm type=text name=start_time id=start_time size='30' value=''> <input type="button" id="start1_time" style="width: 100px" Value="Start Time" onClick="javascript:GetDate();s();"></li> <label class="formFieldQuestion">End Time *</label><input readonly class=mainForm type=text name=end_time id=end_time size='30' value='' > <input type="button" id="end1_time" style="width: 100px" Value="End Time" onClick="javascript:GetDate1(); p();" style='display: none'></li> <input type="hidden" name="hide" /> <label class="formFieldQuestion">Break Time Out </label><input class=mainForm readonly type=text name=break_time_out id=break_time_out size='30' value='' > <input type="button" id="start2_time" style="width: 100px" Value="Start Time" onClick="javascript:GetDate2();tout1();p();"></li> <label class="formFieldQuestion">Break Time In </label><input class=mainForm readonly type=text name=break_time_in id=break_time_in size='30' value=''> <input type="button" id="end2_time" style="width: 100px" Value="End Time" onClick="javascript:GetDate3(); tout2();s();" style='display: none'></li> <label class="formFieldQuestion">Time Utilization</label><input class=mainForm type=text name=time_utilization id=time_utilization size='30' value='' readonly></li> <br /> <br /> <input id="saveForm" class="mainForm" type="submit" value="Submit" style="width : 100px"/> </form> </body> </html> Hi Guys, Hope you can help. My sister has made a web site with a web counter and want to get the counter up by a few hundered. She cannot alter the number manually. Is there a script i can use to get the web counter up by a few hundred? So in other words a web page with java on so it gones on to her site (adds a count) leave it Or refresh it then reload it. Hope i have made my self Clear. thanx, Or even i culd run a web page which loads the page, closes it and load it again. Thanx. Lusa.. Hey Everyone, I'm trying to set up two different buttons that count their own individual clicks. So far I have everything except where one button leaves off, the other picks up. So if I click the left one three times it shows the number 3, and then if I click the button next to it, that button picks up at 4. I want each button to have its own count. Any ideas? Here's what I have so far. <html> <head> <script type="text/javascript"> var counter = 0; function increaseloveit() { counter += 1; document.getElementById('loveit').value = counter; } var counter = 0; function increasehateit() { counter += 1; document.getElementById('hateit').value = counter; } </script> </head> <body> <form> <a href="#" onclick="javascript:increaseloveit();"><input type="button" value="Love It!" name="loveit" onclick="" /></a><input id="loveit" value="0" size="2" /></form> <form> <a href="#" onclick="javascript:increasehateit();"><input type="button" value="Hate It!" name="hateit" onclick="" /></a><input id="hateit" value="0" size="2" /></form> </body> </html> I have the following code but it is not even showing up in the browser. I am very new to JS and very willing to learn. The code was originally found on this site and I have tweaked it and now it doesn't work...Any assistance would be much appreciated. <script type = "text/javascript"> var seconds; var clockId; function startClock(seconds){ timeInSeconds = parseInt(seconds); clockId = setInterval("tick()",1000); } function runClock() { var seconds = timeInSeconds; if (seconds > 60) { // stop at "" seconds alert ("Your time is up!"); clearInterval(clockId); // stop counting return false; } else { timeInSecs++; } var hours= Math.floor(seconds/3600); seconds %= 3600; var mins = Math.floor(seconds/60); secs %= 60; var result = ((hours < 10 ) ? "0" : "" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secondss < 10) ? "0" : "" ) + seconds; document.getElementById("countdown").innerHTML = result; } startClock(0); // start count at 0 seconds </script> <span id="countdown" style="font-weight: bold;"></span> |