JavaScript - Seeking General Coding Tips On My Javascript, Etc.
Hello, I'm new to this forum. I want to improve my ability to write JavaScript and am looking for a friendly place to find some constructive criticism and suggestions on my code.
This script does not have any practical use (that I can think of); it calculates prime numbers. It is just an exercise. I am looking for suggestions on all aspects from the CSS/aesthetics to the HTML and of course the JavaScript. I posted the script here. One definite thing that bugs me is the cursor is not in the text field when the page loads. Also it would be better if the user had the option of hitting the return key in addition to the submit button. Suggestions appreciated. Code: <!DOCTYPE html> <html lang="en"> <head> <title>Prime Number Calculator</title> <style type="text/css"> form{ width: 200px; border: solid 3px blue; border-style: double; padding:5px; text-align:center; background-color:#eee; } #title{ text-align:center; border: solid 1px blue; background-color:#fff; margin:5px; padding:0px; } </style> <script src="jquery.js" type="text/javascript"></script> <script type="text/javascript"> var candidates = new Array(); function calculatePrimes(form){ var max = form.input.value; //Check to make sure input is a number if(isNaN(max)){ alert("Dude, you must enter a number!"); } for(i=2; i<=max; i++){candidates[i]=i;} var i=2; for(i=2; i<Math.sqrt(max); i++){ if (candidates[i]!=0){ var j=i*i; while(j<max){ candidates[j] = 0; j=j+i; } } } //Pull the primes out of the candidates i=2; var primesOut = ""; for(i=2; i<max; i++){ if(candidates[i]!= 0){ primesOut = primesOut + ((i>2)?", " : "" ) + candidates[i]; } } form.output.value = primesOut; } </script> <head> <body> <form> <h2 id="title">Prime-Number Calculator</h1> Check up to:<input type="text" name="input" size="5" value="100" \> <br /> <textarea rows="5" cols="20" name="output"></textarea> <input name="calc" value="Find!" type=button onClick="calculatePrimes(this.form)"> </form> </body> </html> Similar TutorialsHi, To put it bluntly I am a newbie to Javascript. I manage my own site using skills I have developed through learning code and need some help with debugging. My website is www.simplysafes.co.uk, in my IE it tells me I have an error with line 106 and char 2. Can anyone help me with this?? I would really appreciate it. Thanks in advance. James I have a general javascript question. It may apply in this forum but maybe in the asp forum. I have a java applet on a site that I am building. If someone visiting the site doesn't have their javascript turned on, and chooses not to, is there some line of code that I can use that will detect that and replace the applet for an image I create? The site is developed in asp, but being that it is a javascript question, I thought it may apply here. Gary Hi, as the title states, I'm trying to learn some basic javascript, more particularly, jQuery. I HATE having to "allow" active content to run on my IE browser. Is there a way to allow active content permanantly? Instead of having to click allow each time I refresh or reload my test pages? Also, IE keeps freezing or crashing when I run pages with scripts on them. Is this just my browser? or something to do with the active content permissions? Trying to google my questions, but no luck yet. Dear all, I am new here. Need a bit of help. In my company, we have a form that sends an email to a specific address, which is actually our internal helpdesk ticketing system. What we want to do is to make the address of the internal helpdesk ticket system show the person's email address, which is the Requestor_id as mentioned below. This webpage is running on Frontpage Server Extensions. However, when i insert the script in red and tested it on the server, it says that frontpage cannot send out this form due to some errors. Appreciate any form of assistance... Code: <form method="POST" action="--WEBBOT-SELF--" onsubmit="return FrontPage_Form1_Validator(this)" name="FrontPage_Form1" language="JavaScript"> <!--webbot bot="SaveResults" startspan S-Email-Format="HTML/BR" B-Email-Label-Fields="TRUE" B-Email-Subject-From-Field="FALSE" S-Email-Subject="ISP Local User Access" S-Builtin-Fields="" U-Confirmation-Url="../../SuccessMessage.htm" U-Validation-Error-Url="../../FailureMessage.htm" S-Email-Address="Reportticket.GlobalServiceDesk@pr1.xxx.com" S-Email-ReplyTo="<script type="text/javascript"> document.getElementById('Requestor_Email').value; </script>" --><input TYPE="hidden" NAME="VTI-GROUP" VALUE="0"><!--webbot bot="SaveResults" endspan i-checksum="43374" --> I am wanting a script to find and replace numbers in text it is not working for me so will someone help? I believe that this will work. Code: findAndReplace('(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32|33|34|35|36|37|38|39|40|41|42|43|45|46|47|48|49|50|51|52|53|54|55|56|57|58|59|60|61|62|63|64|65|66|67|68|69|70|71|72|73|74|75|76|77|78|79|80|81|82|83|84|85|86|87|88|89|90|91|92|93|94|95|96|97|98)', '(d)'); However, I need the variable a to equal whatever number it finds. (e.g. 27 --> a=27) I have no idea on how to do that These are theformulas that i need it to do Code: var a = _____ var b = 100 - a var c = 17932 % b var d = a + c I'm not a coder myself but I could use some help and am willing to pay if it's within reason. It's for a site I'm putting together for a hobby of mine. Here's a description of what I need done: http://masterengraver.com/ambigrams/test.html Please drop me an email with price for your time if you can do this. Thanks! / ~Sam I have a basic Javascript slideshow that flicks through a series of 6 jpg images very quickly. I also have a button that i need coded so that when a user clicks on the button, the script for the slide show slows down the speed of the flicking images slowly over the coarse of ten seconds and stops on an image. How do i go about coding the button in javascript? I hope this makes sense. Thankyou Here is my code so far. var i, imgs, pic; function rotate() { pic.src=imgs[i]; (i===(imgs.length -1))? i=0:i++; setTimeout(rotate,500); } function diceroll() { pic=document.getElementById("yes"); imgs=["photo1.jpg", "photo2.jpg","photo3.jpg","photo4.jpg","photo5.jpg"]; var preload=new Array(); for(i=0;i<imgs.length;i++) { preload[i]=new Image(); preload[i].src=imgs[i]; } i=0; rotate(); } I have a code that I implemented on my site. I was wondering if there was a way to had an active link within the 'blurb' section? I'm not familiar with Javascript... var blurb = new Array(); blurb[0]="Text 1" blurb[1]="Text 2" blurb[2]="Text 3" blurb[3]="Text 4" blurb[4]="Text 5<br>More text<br>Add a link" blurb[5]="www.link.com" for (i=0; i < aryImages.length; i++) { var preload = new Image(); preload.src = aryImages[i]; } function swap(imgIndex) { document['imgMain'].src = aryImages[imgIndex]; TheText = blurb[imgIndex]; document.getElementById('blurbarea').innerHTML=TheText; } Any help would be great!! I am an amateur web designer and could really use your help. I'm working on a test page right now (http://www.piscatawayacres.com/test.html). I'm trying to have 3 effects going on at the same time, but due to my inexperience with Javascript (I, in fact, copied and pasted most of it), I can't get them to work. To complicate things, my test page works to a certain extent, but when I copy and paste the coding to other pages (like alpacas.html, sheep.html, goats.html, etc.) it ceases to work. I have no idea why it does this. The 3 effects I want to have work: 1. Javascript rollover buttons. 2. A Javascript slideshow--the square picture above the buttons should be changing. 3. I want the image and the buttons to follow the user down the page as they scroll. For some reason though, the buttons (on the couple of pages they work at all) cease to work except at the very top of the page or the very bottom, but not in between. I've been struggling with this obstacle for a long time, so I would greatly appreciate any help someone could give. Thanks so much for your help. PAC P.S. I want to emphasize that some of the coding works on the test.html page, but WON'T work when I copy and paste it elsewhere. I can only assume it is because of conflicts with the coding. I know my coding is not flawless.... Hi, I'm fairly new to javascript & am trying to learn it using best methods. I have been using various books & some video tutorials, such as lynda.com. I've noticed when I do google searches for example tutorials, 9 times out 10, the javascript has been coded into the html file. As a newbie I find it takes a very long time to redo the coding into the separate .js file. And if the coding is relatively complex (and most of it appears that way to someone new to this) I can't get it too work using a separate file for the javascript. I wanted to ask anyone very familiar with this, their suggestions regarding good places for tutorials where the .js file is separated. Apparently there are advantages to having it separate and it's considered best practices from what I've come to understand. Also most of the results from google searches pulls up out-dated coding and/or tutorials that suggest you should already understand what is being referred too. I'm trying to avoid learning it the wrong way. I'm willing to put in the effort, however I don't want to pick up bad habits. Any help is very appreciated. If this was not as clear as I intended it to be, please ask any specifics and I'll try my best to answer. -Todd Okay, I am relatively new to Java and am going to be taking a class on it next fall. For now though, I am trying to code for a client I am currently working with and am hopelessly lost. The client I am working with has an ecommerce site with Network Solutions which uses aspx. It allows you to code html and link to css, java (pretty much anything except php). The problem I am having is that they currently have their product descriptions coded in div tags: <div id='alternatebg'> <div id='detailsgreybox'><div id='alternatename'><p>Alternate Name</p></div></div> <div id='pd2'><p>Not Available</p></div> </div> <div id='usebg'> <div id='detailsgreybox'><div id='use'><p>Use</p></div></div> <div id='pd3'><p>Chemicals</p></div> </div> What they want to happen is for the sections that have 'Not Available' as the answer to not show up on the live page. I have tried to use <ns:if condition="..."> but do not know how to call for it to see if the div says 'Not Available'. Any help is greatly appreciated as I can not move forward until I can figure this out. Hi Experts, I'm new to this forum and need your help regarding javascript. I am creating a roster for my team with a web interface. Ex: A picture is attached for your reference The time is in IST (+5:30) I have created a drp down list which has PST, EST,CST time. I need to write a code so that whenever I select any of these times (PST,EST,CST, MST, IST) , it should automatically update the table. Please help. Regards, Indy Hi, I have been downloading and examining "gallery building" software and I find none of it links to an e-commerce option. Does anyone out there know the quickest way I can create a truly simple sales website which supplies a payment procedure for photos in an online gallery, thereby allowing javascript to #1 display a larger hover on mousover and #2 (on mouseclick) link photos (my gallery material) to an e-commerce component which offers a "payment procedure" to people visiting my gallery, specifically "bank transfer, credit card, check, PayPal etc." and will allow them to purchase my photos. The photos would be not the "large hover" ones watermarked with my own logo, but would be #3 the (presumably cached) clean, downloadable photos of a higher resolution represented by the watermarked photos and intended for sale. This would I assume then include a "download photo" page as part of the e-commerce "payment procedure" allowing non-watermarked photos cached safely outside the viewable gallery to be purchased. It sounds like such a breeze, (#1,#2,#3) and I find javascripting with little fragments of these codes, (have even been admiring the free code offered by several programmers which opens thumbnails on hover etc.) but none of it (#1,#2,#3) all stitched together. Anyone capable of this? Hello all out there I am going to post this in 2 separate views. I am working on an assignment from this link http://books.google.ca/books?id=aG_T2aD ... MonthCell()&source=bl&ots=EJXyGF-tbI&sig=vbgqgua2uSaL6DWp0Rx_BYoZ0z8&hl=en&ei=9C7gTLmiAYaXnAeywLWRDw&sa=X&oi=book_result&ct=result&re snum=1&ved=0CBcQ6AEwAA#v=onepage&q=writeMonthCell()&f=false if u scroll down to case 1 is what I am working on included in the case are 2 other files as to the one i have to work on i used all the proper steps and instructions and i think I have the correcting coding for my form however my program still does not work here is the exact code i am using let me know if anyone sees any errors, as I am convinced i have it correct? Here is my code: <html> <head> <!-- New Perspectives on JavaScript Tutorial 3 Case Problem 1 The Lighthouse Author: John Res Date: November 14 2010 Filename: clist.htm Supporting files: lhouse.css, list.js, logo.jpg --> <title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> <script type"text/javascript" src"list.js"></script> <script type="text/javascript"> function amountTotal() { // return sum of values to amount array total=0; for(var i=0; i<amount.length; i++) { // set variable to 0 total+=amount[i]; } return total; } </script> </head> <body> <div id="title"> <img src="logo.jpg" alt="The Lighthouse" /> The Lighthouse<br /> 543 Oak Street<br /> Delphi, KY 89011<br/> (542) 555-7511 </div> <div id="data_list"> <script type=”text/javascript”> // set up variables of rows and cellspaces document.write(“<table border=’1′ rules=’rows’ cellspacing=’0′>”); document.write(“<tr><th>Date</th><th>Amount</th><th>First Name</th>”); document.write(“<th>Last Name</th><th>Address</th></tr>”); for (i=0; i< amount.length; i++) { // create a loop in counter of variable starting at 0 and increase of 1 increments if (i%2==0) document.write(“<tr>”); else document.write(“<tr class=’yellowrow’>”); // have every row with a yellow background use a loop document.write(“<td>”+date[i]+”</td>”); document.write(“<td class=’amt’>”+amount[i]+”</td>”); // have values of the dates document.write(“<td>”+firstName[i]+”</td>”); document.write(“<td>”+lastName[i]+”</td>”); document.write(“<td>”); document.write(street[i]+”<br />”); document.write(city[i]+”, “+state[i]+” “+zip[i]); // zip arrays for address document.write(“</td>”); document.write(“</tr>”); } document.write(“</table>”); </script> </div> <div id="totals"> <script type=”text/javascript”> // use script elements in HTML document.write(“<table border=’1′ cellspacing=’1′>”); document.write(“<tr><th id=’sumTitle’ colspan=’2′>Summary</th></tr>”); document.write(“<tr><th>Contributors</th>”); document.write(“<td>”+amount.length+”</td></tr>”); document.write(“<tr><th>Amount</th>”); document.write(“<td>$”+amountTotal()+”</td></tr>”); document.write(“</table>”); </script> </div> </body> </html> thanks everyone Hi I have been trying to create a form using Django for a very long time but have not been able to get it to look the way I want. Someone suggested to me that I should use Javascript (Jquery) to do this. Here's what I want to do. For the form I want, there are certain statuses at the bottom, like "Done", "Incomplete" and etc. When the form is filled in, the person will click on one of these statuses. What I want this button to do is to save the page/form and also to generate a few new links relating to the status selected. For example, if the person selects "Done" this should save the form and generate two new buttons. One that says "Close" which would take you to the home page, and one that says "Continue" which would take you to the next form. My problem is that I'm new to Django and have no experience with Javascript. So if anyone could help or give me hints that would be greatly appreciated. I'm working on a new custom theme for my WordPress based site, and up until now I've been using the following PHP code to color code links based on whether the post was in the "Wii" category, "Xbox" category, or "PlayStation" category: PHP Code: <li> <?php if (in_category(3) ) { ?> <a style="color:#990000;" href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a> <? }elseif (in_category(4) ) { ?> <a style="color:#669900;" href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a> <? }elseif (in_category(7) ) { ?> <a style="color:#0099cc;" href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a> <? } else { ?> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> <? } ?> </li> Thing is, I've now installed a plugin called "Recently Popular" that logs all visits and can output which posts were viewed the most in the past X days/weeks/months/etc. and the author has it set up to only allow HTML formatting via this line: PHP Code: <?php get_recently_popular(1, 'WEEK', 5, 0, 0, '<a href="%post_url%" rel="bookmark" title="%post_title%">%post_title%</a>'); ?> I've tried sticking PHP in the line, but it only takes HTML. I've tried sticking one of these lines in each of the conditional statements above, but realized that this line outputs the entire "Recently Popular" list, not just one item - so everything would end up being the same color still. I contacted the plugin author, who said that without hardcoding there's no way to get around this via the plugin, but that outputting it normally and running it through JavaScript might give me a way to apply CSS styling to it after it's been rendered. I'm not experienced with JavaScript, unfortunately... does anyone know how I can do this? Hi, I'm still in the early stages of learning Javascript so I'm not sure how (or if it's possible) to do this. I know HTML, CSS, etc... just not too familiar with Javascript. Here's the deal.... I run a website that features a chat room written in Perl for CGI. The chat room will automatically email a user their password if it's forgotten but there is one issue.....it does not have the "Forgot Password?" link. To achieve the Lost Password page, the user must enter an invalid password FIRST on the login screen, otherwise they cannot get to that option and are often requesting assistance. What I had in mind was an easier way for the user to get their password since new novice members are not sure how to get to the lost password page. I'm not trying to edit the Perl code for the chat, but I wanted to build a "Forgot Password?" page using a Javascript code that will automatically take their username from the "username" login field and direct them to the lost password page which would be "chat2.cgi?action=send_pwd&name=..." I'm sorry if this is confusing, I'm not sure that I am explaining this right. When the user enters an invalid password, it takes them to the lost password page which contains a link "lost password" and will automatically email them their login details when clicked on. When they click that link, the URL contains the string "chat2.cgi?action=send_pwd&name=username" What I would like to do is put a link on the login page (like most normal chat rooms have) that says "Forgot Password?". When clicked on, I want it to take them to a page where all they have to do is enter their username in a form and click Submit, then have a Javascript code automatically extract their username from that field and insert their username automatically to the end of that URL (chat2.cgi?action=send_pwd&name=...) where ... would be the name extracted from that form field. This would result in the browser taking them to that URL which would trigger the chat to automatically email the password. Can I do this with Javascript?? If so, any help would be greatly appreciated! I need help calculating the average for a Practical Exam 1) the teacher asked us to create a for loop and prompt the user to enter 10 numerical grade. (which I did) 2) She wants us to find the average of the user's 10 entry, and give them their final grades (ex: user enters 80, 90, 70, 90 etc.., the counter will stop prompting for entry after the 10th entry) I need to display, your final grade for the class 85, you've got a B) I need help figuring out the average formula! Please, i need to e-mail the teacher my practical by 10 PM (eastern time). Thank you, victory1 Okay so I'm trying to come up with as many alternative methods to accomplish something. So I'm just seeking input from anyone who is willing to supply some. After the user clicks on a match type it'll know HOW MANY sides to the match there are so say for a singles match it'd have 2 sides (1 vs. 1) for a Triple Threat Match it'd have 3 sides (1 vs. 1 vs. 1) and so on. All matches have a stored field in the database of how many sides they have. So I'm thinking that I could have it create 3 divs (or something) down in the competitors area of how many sides there are in the match (separated by a VS. text block) and when the user selects a character from the dropdown and adds a character the user can maybe drag and drop the character's name to whatever side they choose. Its one idea. If you think of an EASIER more EFFICIENT way to do something like this and have an idea say something please or even if you can't let me know that you think it's a worth while idea. Code: <label for="matchtypedrop<?php echo $i+1 ?>">Match Type:</label> <select class="dropdown" name="matchtypedrop<?php echo $i+1 ?>" id="matchtypedrop<?php echo $i+1 ?>" title="Match Type <?php echo $i+1 ?>"> <option value="0">- Select -</option> <?php $query = 'SELECT id, matchtype FROM matchtypes'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['matchtype']."</option>\r"; } ?> </select> <label for="competitors<?php echo $i+1 ?>">Competitors:</label><ul id="competitors<?php echo $i+1 ?>" style="list-style: none; margin-left: 195px;"></ul> <select class="dropdown" name="charactersdrop<?php echo $i+1 ?>" id="charactersdrop<?php echo $i+1 ?>" title="Characters Dropdown <?php echo $i+1 ?>" style="margin-left: 195px;"> <option value="0">- Select -</option> <?php $query = 'SELECT id, `character` FROM characters ORDER BY `character`'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['character']."</option>\r"; } ?> </select> <input type="button" value="Add Character" class="" onclick="Competitors(<?php echo $i+1 ?>)"/> Hi, I've been looking for a client-side form validation script which will check each field before submitting the form. Can anyone point me to a good one that looks professional. I want it to make a nice presentation of any errors as well, perhaps, as showing a 'tick' sign when the field is correctly filled in . bazz |