JavaScript - Need Help With Simple Javascript And Html
Hi everyone,
I am new to javascript, i have not read any books, but i am trying to figure out the language on the go. I am stuck with a simple program that i am trying to create for a class project. Any suggestions or help would much appreciated. My code is very simple in which i would like to convert a number value into different format of temperature. My code is listed below, it is not working in the browser. Help me fix it. ********************************************************* <!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 content="text/html" http-equiv="Content-Type" /> <title>E6B temp conversion</title> <script type="text/javascript"> function ConvertTempToC(TempConversionC) { var temperature = TempConversionC.F.value; if (temperature.length > 0) { TempConversionC.TempC.value = Math.round(5/9 * (temperature - 32)); document.write(TempConversionC.TempC.value); } } </script> </head> <body> <b>Fahrenheit to Celsius</b> <br/> <input size="6" name="F"/> <br/> <input onclick="ConvertTempToC(this.form)" value="Calculate Celsius" type="button" name="Submit11"/> <br/> <input readonly="readonly" size="6" name="TempC"/> </body> </html> Similar TutorialsI'm trying to convert A world Population Counter from Flash into HTML/Javascript. But I'm having difficulties and It would be great if someone can help me out. The sample show a analog clock, But the html version I want should use just a digital clock, it's simpler I think http://www.webstylelabs.com/worldclock2.swf http://www.webstylelabs.com/actionscript.txt Here is my code, http://www.webstylelabs.com/clock.html So just plain input digital counter is ok I appreciate any help I am very new to javascript and really can't figure out what I am doing wrong. I am trying to make a 1 page store that allows you to type in an item and select the color and size you want for that item. If you don't fill in a field, an alert message should tell you that. If all the fields are filled in, a "thank you for purchasing ____________" message should appear in a text area at the bottom of the page. This is my current code: Code: <html> <head> <script> function processform() { if ( document.form1.item1.value == "") { alert("No Item Chosen") } else { chosen = "" len = document.form1.c1.length for (i = 0; i <len; i++) { if (document.form1.c1[i].checked) { chosen = document.form1.c1[i].value } } if (chosen == "") { alert("No Color Chosen") } } else { itemname = document.form1.item1.value; itemcolor = document.form1.c1.value; itemsize = document.form1.size.value; document.form1.txtarea1.value = "Thank you for purchasing a " + itemsize + " " + itemcolor + " " + itemname; } } </script> </head> <body> <h1>Store</h1> <br/><br/> <form name="form1"> <h4>What item would you like to buy?</h4> <input type="text" name="item1" value="" /><br /> <br/><br/> <h4>Color</h4> <input type="radio" name="c1" value="blue" /> Blue<br /> <input type="radio" name="c1" value="red" /> Red<br /> <input type="radio" name="c1" value="green" /> Green<br /> <input type="radio" name="c1" value="yellow" /> Yellow<br /> <br/><br/> <h4>Size</h4> <select name="size"> <option value="small">Small</option> <option value="medium">Medium</option> <option value="large">Large</option> <option value="extra large">Extra Large</option> </select> <br/><br/> <button onclick="processform()">Purchase</button> <br/><br/> <textarea rows="2" cols="40" name = "txtarea1"> </textarea> </form> </body> </html> When I press the purchase button, no alert message is shown, nor does anything get displayed in the textarea. What am I doing wrong? I imagine this would be very simple for someone who knows javascript. I want to have three fields. First field is "posted speed limit", second field is "actual speed" and third field will be the output field. All the script needs to do it subtract the posted speed from the actual speed and add a ZERO to the end; which is the amount of the speeding ticket. The minimum fine is $100, however. So, 5 miles over the speed limit would be $100 (minimum value) 15 miles over the speed limit would be $150 (add a zero) 35 miles over the speed limit would be $350. etc. I know very little Javascript, if anyone could help me out with this, I'd appreciate it. Thanks, Sean favorite I'd like to modify a form on www.formsite.com (form builder app): username: testuser password: password I would like to use the nicedit.com's inline content editor's js to transform my textarea's into a richtext area. At present the nicedit editor works well in creating the richtextarea. However, the KEY point is that I would like formsite's form to pipe in the the created html and render it with the html component of formsite. Currently, the pipe function in formsite will only put out the html syntax in it's html module. action seen he http://fs8.formsite.com/testform/form1/index.html So this would be: 1. checking out my form on formsite.com 2. the script from nicedit.com is already installed in an html component. 3. changing or telling me the scripts/tags/or whatever for formsite form using formsites form builder (which allows some html/script editing). 4. changed so as to render the rich text entered on page 1 in page 2 instead of the html syntax. Any other solutions using formsite and any other richtextarea solutions would be great too! Hello! This is my first post here. I am not a programmer and I thought you guys would be able to help me. I have this script in one of my pages. It was written by a former coworker. It worked perfectly in Firefox 3.6 but stopped working after browser upgrades. It may be a simple fix... I just don't know. Any help would be GREATLY appreciated. Here is the code in the HEAD: Code: <script type="text/javascript"> function generateAnswer() { //alert("answersheet"); window.open("answerSheet.html" + window.location.search); } </script> And here is the code in the BODY, where the script is called: Code: <p>Generate the answer sheet for the tests you have selected: <a href="javascript:generateAnswer()">Generate</a></p> When the page runs, I can see the "Generate" link, but it takes me nowhere. I'm trying to code a set of buttons that upon being pressed, change an image on the other side of the table in which they're located (not themselves). Is there a way to do this and if so, what would it be? So far I've been trying to use onMouseDown and changeImage with object id tags to get the effect but it's not working. i have this simple js example to click Delete Post and then give the user two options. If they click yes then they go that page...but how do i set it to where when they click cancel it goes back to "Delete Post" ??? i suck at javascript Code: <html> <body> <p><b>Delete Post</b></p> <script type="text/javascript"> window.onclick=function(){ document.getElementsByTagName("p")[0].innerHTML="<b><a href='#'>Delete</a> || Cancel</b>" } </script> </body> </html> Hi, I have some Javascript, what I want to hapen is, when the variables hour and randomhour are the same, the message hello is displayed. What actually happens is the message will display all the time, and dissapear when randomhour is 0. Here is my script: Code: <script type="text/javascript"> //Gets hour and minute of day var d = new Date(); var hour = d.getHours(); var minute = d.getMinutes(); //Generates a random hour and minute var randomhour=Math.floor(Math.random()*24) var randomminute=Math.floor(Math.random()*60) document.write(hour); document.write(minute); document.write("----"); document.write(randomhour); document.write(randomminute); if (hour = randomhour) { document.write("<b>Hello</b>"); } </script> I'm brand new to javascript and have a simple assignment that I'm stuck on. I would appreciate any help. Here's what I want: 0:0 1:1 2:3 3:6 4:10 5:15 As you can see, I want the numbers after the colon to be a sum of the number to the left and the number above it. I can easily get the number before the colon, but not sure how to get the sum (the number after the semicolon). Here's my code so far: <html> <body> <script type="text/javascript"> N=0; while (N<=5) { document.write(+ N); N++; document.write(":"); document.write("<br />"); } </script> </body> </html> I need to use a loop, hence the "while" loop. But not sure how to set up variables to do the addition. Thanks much for any help - as you can see, I'm not a programmer. Hi guys, I have this piece of php code: PHP Code: <?php $file = 'counter.txt'; $data = @file($file); $data = $data[0]; if($handle = @fopen($file, 'w')){ $data = intval($data); $data++; fwrite($handle, $data); fclose($handle); } ?> What I need to know is, can javascript activate this piece of php code with an onclick function to make it write to the txt file? I have a link that downloads a file and would like to add a little javascript onclick function to write to the text file (as in the php code above) at the same time as they download the file. I was not sure if this was possible in the same way you would do something like: window.location.href='http://www.yoursite.com'; Any help is hugly appreciated. Kind regards, paffley Can anyone help me with doing this? I'm kinda new to JavaScript! Create an Array (list) containing 10 words. For every half second going word by word appears in a <span> element. When all the words in the list are gone through, the interval shall stop and printing "The End". I've been given the challenge of creating a simple simulation in Javascript and html. Here are the criteria: - A bunny occupies a meadow that is 30 units wide and 30 units long. - The bunny has a limited amount of energy. 1000 units to start. - The bunny can only move one spatial unit per unit time. Each movement may be in any direction. - Each time the bunny moves, it spends 1 unit of energy. - The meadow is bathed by sunlight, and the soil is fertile and rich. Plants grow in the meadow. These plants can be eaten by the bunny. Each plant boosts the energy of the bunny by ten units. When the plant is eaten by the bunny, it should no longer be present in the meadow. - Plants grow at random in the meadow. - Plants boost the bunny's energy by 10 units - No two plants may occupy the same space in the meadow. So far, I have the bunny moving properly and its energy adjusting properly, but I can's seem to figure out how to visually add plants to the meadow. My current code is below: HTML: Code: <div id="energyFeedback" style="width:300px; height:10px; border:1px solid #666;"> <div id="energyFeedbackBar" style="width:100%; background-color:#999; height:100%;"></div></div> <div id="gameContainer" style="position:absolute; top:30px;"> <div id="meadow" style="width:300px; height:300px; background-color:#957E52; position:absolute; left:0px; top:0px;"> <div id="bunny" style="position:absolute; height:10px; width:10px; background-color:#FCC;"></div> </div> </div> JS: Code: //The bunny will start in the center of the meadow... therefore 15units in x & 15units in y directions var bunny = {name: "Bunny", x: 15, y: 15, energy: 1000}; //as plants are created, they will get pushed into this array: var allPlants = []; //Graphic stuff // Create a reference to the HTML element on screen so that you can move it around bunny.graphic = document.getElementById('bunny'); energyFeedbackBar.graphic = document.getElementById('energyFeedbackBar'); //growthFactor will determine how likely a plant is to grow. Modify this value to answer the question above. var growthFactor = 0.5; //make a list of directions of travel for our Bunny var directions = [ n = {x: 0, y: -1, name: "North"}, e = {x: 1, y: 0, name: "East"}, s = {x: 0, y: 1, name: "South"}, w = {x: -1, y: 0, name: "West"},]; //setInterval will make the program run every 100ms (in this case) var int = setInterval(Simulation,100); //intervalCount will keep track of our units of time expended var intervalCount = 0; //clear the interval (once the angriest bunny has been determined) function stopInt() { clearInterval(int); }; //this function gives a random element from an array (directions in our case) function randomElement(_array) { if (_array.length == 0) throw new Error("The array is empty."); return _array[Math.floor(Math.random() * _array.length)]; }; //the moveBunny function will take the bunny and and move it in a random direction function moveBunny() { // if the bunny is still alive... if (bunny.energy > 0) { //choose a random direction by running our "directions" array through our randomElement function. var directionOfMovement = randomElement(directions); //the bunny's position is changed by adding a random value to his x and y coordinates var newPosX = bunny.x + directionOfMovement.x; var newPosY = bunny.y + directionOfMovement.y; //we must constrain the bunny's movement to within the 30 by 30 meadow if (newPosX < 0 || newPosX > 30) { //basically, if the bunny lands beyond 30px or before 0px in the x or y directions, // their value gets reset to the min or max distances. if (newPosX > 30) { bunny.x = 30; } else { bunny.x = 0; } } //If they fall within the meadow, the bunny's x and y value are now updated to the new value. else { bunny.x = newPosX; } if (newPosY < 0 || newPosY > 30) { if (newPosY > 30) { bunny.y = 30; } else { bunny.y = 0; } } else { bunny.y = newPosY; } } else{ stopInt(); }; //move bunny graphically on the browser. bunny.graphic.style.left = (bunny.x * 10) + 'px'; bunny.graphic.style.top = (bunny.y * 10) + 'px'; console.log(bunny.name + " moved to x: " + bunny.x + ", y: " + bunny.y + ", " + directionOfMovement.name); //bunny's health is reduced by 1 unit per movement. bunny.energy -= 1; //represent this graphically in the browser by adjusting the width of the energyFeedbackBar to represent the bunny's current energy level. energyFeedbackBar.graphic.style.width = (bunny.energy/10)*3; console.log(bunny.name + " has " + bunny.energy + " units of energy left."); }; function createPlant() { //*********************************Here is where the problem begins...*********************************** //the plant needs to appear on the screen as a small green square (approx 5 by 5px) within the 30 by 30px meadow. //Every plant created must be pushed onto the array 'allPlants' so that it can be compared to the position of the bunny. //I thought that maybe divs could be dynamically generated but I'm not sure if this is the most effective way, or if I'm even doing this properly. I tried this below: /*var plant = document.createElement("div"); plant.id = "plant" + intervalCount; plant.style.x = Math.floor(Math.random()*30) + "px"; plant.style.y = Math.floor(Math.random()*30) + "px"; plant.style.width = 5 + "px"; plant.style.height = 5 + "px"; plant.style.background = "#090"; document.documentElement.appendChild(plant); console.log("plant created at x: " + plant.x +" and y: " + plant.y);*/ }; //Simulation will determine whether a plant grows, //...moves the bunny //... and compares the position of the bunny to the position of all the plants. function Simulation(){ //To keep track of time, add to the intervalCount intervalCount++; //state time in the console console.log("Time: " + intervalCount +" units"); //grow a plant randomly (dependant on the growth factor) if (Math.random() < growthFactor) { createPlant(); } //move the bunny moveBunny(); // Compare bunny's position to the plants' positions, if there are plants. if (allPlants.length >= 1) { for (var j = 0; j < allPlants.length; j++) { // compare x and y co-ordinates if (bunny.x == allPlants[j].x && bunny.y == allPlants[j].y) { console.log("The bunny ate a plant!"); //increase bunny's energy bunny.energy = bunny.energy + 10; // *********Here the plant must also be removed from allPlants and removed visually from the meadow*********** }; }; }; }; Any help with this generation of plants would be appreciated! I would like to compare my work to the work of others, can you please solve this and post your result? Declare an 8 x 8 matrix and an array of length 22. 1.- Populate the matrix. 2.- Copy the elements of the first row of the matrix, the anti-diagonal, and the last row of the matrix into the array, to form a Z shape. 3.- Sort the array. 4.- Assuming that the data in the arrays are grades, compute the average of the grades stored in the even locations of the array. 5.- Copy the array back into the matrix.(back into the Z) 6.- Print out the matrix values. Hi i am trying to combine these two statments Code: searchValue.replace( /\[[^\)]*\]/g,""); searchValue.replace( /\([^\)]*\)/g, ""); is it possible to put these two into one statment? also is there a javascript function which does the same as urlencode? many thanks Luke Hello! I have a few simple questions and I'm not having any luck with my Google searches. Any information is appreciated! Pardon my pseudo-coding... It's the simplest way to describe what I'm looking for. 1. I have a two dimentional array called List. I want to write a for loop to loop through the first dimension of the array. How is this done? Code: for (Line in List[][]) { write ( List[Line][1] + " = " + List[Line][2] + "<br/>"); } 2. Is there a simple example of how to create and use an object with multiple properties, functions, etc? For example, the following "person" object: Code: Person as object - property FirstName as string - property LastName as string - function Name = property FirstName + " - " + property LastName - property Children[] as array of Person objects - property Gender as string - property Mate as Person object - property DOB as date 3. Can enumeration be done easily in Javascript? Code: enum StatusFlags blank as 0 new as 1 free as 2 reserved as 4 sold as 8 endedum enum StatusDecoration new as "bold" old as "normal" free as "green" notfree as "red" reserved as strikethrough"" unreserved as "no-strikethrough" sold as "italics" unsold as "no-italics" endenum Thanks! I'm new to javascript but not to programming. Here is my code: PHP Code: PHP Code: print "<form name='goldcalculator'>"; print "<input type='hidden' name='goldspot' value='$goldvalue'>"; print "<select name='gunit' onchange='updateTotal();'>"; print "<option value='20'>Pennyweight (DWT)</option>"; print "<option value='31.1'>Grams (g)</option>"; print "</select><br>"; print "10K <input type='text' name='10k' onchange='updateTotal();'><br>"; print "14K <input type='text' name='14k' onchange='updateTotal();'><br>"; print "18K <input type='text' name='18k' onchange='updateTotal();'><br>"; print "22K <input type='text' name='22k' onchange='updateTotal();'><br>"; print "24K <input type='text' name='24k' onchange='updateTotal();'><br>"; print "TOTAL <input type='text' name='totalprice'>"; print "</form>"; Code: <script language="JavaScript"> function updateTotal() { var u = document.goldcalculator.gunit.value; var spotprice = document.goldcalculator.goldspot.value / u; var gold10 = document.goldcalculator.10k.value; var gold14 = document.goldcalculator.14k.value; var gold18 = document.goldcalculator.18k.value; var gold22 = document.goldcalculator.22k.value; var gold24 = document.goldcalculator.24k.value; var calculatedPrice = document.goldcalculator.totalprice.value; calculatedPrice = ((spotprice*.999*gold24)+(spotprice*.916*gold22)+(spotprice*.75*gold18)+(spotprice*.585*gold14)+(spotprice*.417*gold10)); } </script> I don't know where to begin to debug this. It's very simple. The $goldvalue variable is non-editable and is pulled off my MySQL database and that works. They fill in the inputs via the PHP form and then it basically adds them up and spits out the total. Can someone tell me what's wrong? Hi guys I have what i think is a fairly simple script used for an image gallery with a next and back button. It seems to work pretty well, but i would like to make the gallery scroll round... ie when the user reaches the last picture and presses the next button again, the first image will be displayed again - and visa versa with the first image and the back button. Below is my JS, can post the small amount of HTML that calls it if necessary. Any help MUCH appreciated, been messing around with it for ages and being the newbie i am, can't seem to find any way of doing it Code: // List image names without extension var myImg= new Array(6) myImg[0]= "performance2011"; myImg[1]= "performance2005"; myImg[2]= "performance2006"; myImg[3]= "performance2007"; myImg[4]= "performance2008"; myImg[5]= "performance2009"; myImg[6]= "performance2010"; // Tell browser where to find the image myImgSrc = "../images/"; // Tell browser the type of file myImgEnd = ".jpg" var i = 0; // Create function to load image function loadImg(){ document.imgSrc.src = myImgSrc + myImg[i] + myImgEnd; } // Create link function to switch image backward function prev(){ if(i<1){ var l = i } else { var l = i-=1; } document.imgSrc.src = myImgSrc + myImg[l] + myImgEnd; } // Create link function to switch image forward function next(){ if(i>5){ var l = i } else { var l = i+=1; } document.imgSrc.src = myImgSrc + myImg[l] + myImgEnd; } // Load function after page loads window.onload=loadImg; I have a list with two items: Code: <select name="gateway" id="gateway"> <option value="2">PayPal</option> <option value="1">Credit/Debit Card</option> </select> When the second list item is selected, a div with several input fields needs to appear: Code: <div id="hidden_field"> Input fields are placed here. </div> Likewise, if someone selects the first list item, the div should not appear. Does anyone know how to do this with javascript? I am very new to javascript, so your help is greatly appreciated! Hello guys, Im new to Javascript,please help me ya in my php code, I retrieve a ID value and assign to variable like below PHP Code: $id = $gettingdata['id']; and I want this id to be include together with javascript "insertsubcat" function like below Code: <a href="javascript:insertsubcat('.$ID.');"/>Click to insert this data</a> in the javascript page, I dont know how to call back the id value and i try like code below but it doesnt work Code: function insertsubcat(data) { var data = data.value; . . . . } Any idea? Thanks Azhan Malaysia |