JavaScript - Js Numeric Guessing Game
Absolutely nothing happens when I click on the button, and I know NOTHING about Java. Need serious help!
The user is supposed to arbitrarily type a number (1-5) and see if it's the same one that JavaScript generates. The function "secretNum" is supposed to be a global variable, but I don't have a clue as to what that means. Anyways, an alert should pop up saying either congrats or try again. Code: <html> <head> <title>Guessing Game</title> <script type="text/javascript"> function setUp () { secretNum = 1+Math.floor(5*Math.random()); alert = (secretNum); } function checkGuess () { userGuess = document.IfForm.guessBox.value; userGuess = parseFloat(userGuess); // get value from text box if (secretNum == userGuess) {alert ("Correct!");} else {alert ("Sorry, Try Again");} } </script> </head> <body style="text-align:center" onLoad="setUp();"> <h2>Guess the Number From 1 to 5</h2> <form name="IfForm"> Enter Your Guess: <input type="text" size="5" name="guessBox" value="" /> <br /> <input type="button" value="Check Guess" onClick="checkGuess" /> </form> </body> </html> Similar TutorialsCan someone guide me to what I am doing wrong. My book does not show how to do this. This is what I have to far.I am just getting more and more confused. I am suppose to have a button there asking write a timeout that asks users if they want to stop the game if they do not press the Guess button within 10 seconds. They are suppose to pick a number between 1-100. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Guessing Game</title> <script type="text/javascript"> while (runAgain == 'y' || runAgain == 'Y') { guessedNumber = reader.readDouble("Please pick a number between 1 and 100: "); while (guessedNumber != randomNumber) { if (guessedNumber < randomNumber) System.out.println("Too low!\nGuess again!"); else if (guessedNumber > randomNumber) System.out.println("Too high\nGuess again!"); else if (guessedNumber == randomNumber) System.out.println("You got it!"); } runAgain = reader.readChar("Play again (y/n)? "); } </script> </head> <body> <div id="content"> <h2>JavaScript Guessing Game</h2> <p>Enter a number between 1 and 100, then press the Guess button.</p> <form action="myForm" method="post"> <p><input type="text" name="guessgame" /> <input type="hidden" name="eGame" value="1"/> <input type="submit" value=" Guess" name="submit"/></p> </form> </body> </html> What I'm trying to achieve is it initialises a number between 1-2000 randomly. When the submit button is clicked it simply returns if the number that is in putted is higher or lower than the randomly initialised number. External JavaScript: Html Code: <html> <head> <script type="text/javascript" src="jsscri.js"></script> </head> <body onload="initialisation ()"> <form name="exampleform"> <h3> Number: <input name="number" type="text" onchange='checkNumber( this.value );'> </h3> <p> <input name="submit" type="button" value="Guess" onclick= 'checkValue()';/> </p> </body> </html> If you load this onto a webpage you'll see what i'm trying to do. I tried deleting the rest of the code to keep the size of the code down. Hi everyone. Right now I'm doing a guessing game assignment for my class. I'm new to the forums so sorry if copy/pasting code into the thread here isn't the right thing to do. I have ran firebug a few times on this code and for some reason the variable "Football" is the only answer that is declared true. How can I fix this code so that all of the variables in the array display the true statement when typed in the box? Note: I have the questions looped to ask 3 times. Thanks! <html> <head> <h1>Welcome to the guessing game!</h1> <h2>Second Submission Attempt</h2> </head> <body> <script type = "text/javascript"> var sportsAry = new Array(6); sportsAry[0] = "Football"; sportsAry[1] = "Basketball"; sportsAry[2] = "Rollerblading"; sportsAry[3] = "Hiking"; sportsAry[4] = "Biking"; sportsAry[5] = "Swimming"; var firstName; var points = 0; var finalscore; var ask; do { firstName = prompt("Please enter your first name.",""); } while (firstName == "" || firstName == null || firstName == parseInt(firstName)); alert("Welcome to the Game, " + firstName + " !"); for (var count = 0; count < 3; count++){ ask = prompt("Please guess a sport : ",""); if (ask == null){ alert("You are chicken!!!"); } else if (ask == ""){ alert("You forgot to enter a game!"); count--; }else { for ( var i = 0; i < sportsAry.length; i++){ if (ask.toUpperCase() == sportsAry[i].toUpperCase()) { points +=5; alert("You have guessed correctly! You have gained 5 points"); break; }else if (ask.toUpperCase() !== sportsAry[i].toUpperCase()) { points -=5; alert("You have guessed incorrectly, you gain no points."); break; } } } } if (points == 15){ document.write(firstName + ", you are a mind reader!" + "<br>"); } else if (points < 15){ document.write(firstName + ", you are pretty good!"); }else { document.write(firstName + ", you do not display ESP tendencies at this time."); } </script> </body> </html> Hello! So, here is my problem. I have to write a number-guessing game that prompts the visitor to guess the right number in a maximum of 4 attempts. If the visitor guesses the target number within 4 tries, I want to write an alert that congratulates them as well as indicates the number of tries taken. If they guess incorrectly, I want to prompt with "Try again." And I finally want to keep track of each number they typed with a document.write. I have something like this, but its just not working out: Code: <script type="text/javascript"> var count = "" ; if (count >=0 && count <=88) { for (i=1; i<=4; i++) { count = prompt("I'm thinking of a number between 0-88. Can you guess it?", ""); document.write("Guess #" + i + ":" + count + "<br />"); }} else if (count>88){ alert("Too high!") } else if (count=55){ alert("Congratulations, you guessed it in " + i + " tries!) } else{ alert ("Guess again!") } </script> Thank you for your time. Im making a simple "gallow" guessing game. I got a virtual keyboard styled with boxes and onclick event, and a randomized guessing word when i click on button new game. Here is the virtual keyboard: Code: <div align="center" style="width: 700px; float: left;" id="keys"> <span onclick="selection(this)">Q</span> <span onclick="selection(this)">W</span> <span onclick="selection(this)">E</span> <span onclick="selection(this)">R</span> <span onclick="selection(this)">T</span> <span onclick="selection(this)">Z</span> <span onclick="selection(this)">U</span> ... all keys + a .css for looking like a keyboard - see picture at bottom</div> The function that randomizes a word from the array of words + css styled boxes around the word chars. the array of words: Code: var strings= [ "indexof", "round", "fixed", "touppercase", "alert", "prompt"]; Code: function newgame() { document.getElementById('display').innerHTML = ""; var wordArr = strings[Math.floor(Math.random() * strings.length)].split(""); for (var i=0; i<wordArr.length; i++) { document.getElementById('display').innerHTML += '<span>'+wordArr[i]+'</span>'; } } css for this words Code: #display span { border-top:1px solid #000; border-right:1px solid #000; border-bottom:1px solid #000; width:10px; background-color:gray; text-align:justify; padding:5px 10px; } #display span:first-child { border:1px solid #000; } I also have function to colorize the pressed key on virtual keyboard-that colors it red-so the user knows it pressed it already Code: function selection(key) { key.style.background = "red"; } So now i have the question how do i make the guessing word - the boxes around chars without the chars - that the boxes are empty, but somehow the word stays in back of it or something like that -temporary save?.. I mean now i got [f] [i] [x] [e] [d], i wanna when i press new game to be like [] [] [] [] [].. and then i need to guess the word.. i press e on keyboard.. then it comes like this [] [] [] [e] []... Somehow i need to check if the pressed key on the keyboard is inside the word, and then show it in the box (but how).. then i press f -> [f] [] [] [e] [] .... and so on till i guess all of the word.. Here is an screenshot if u dont know what i mean.. http://img13.imageshack.us/i/printscreenshot1.jpg/ Thank you for helping! Good day. I'm working on a word guessing game. Simple premise, enter a letter, if it's in the mystery word it fills the asterick if not you keep guessing until it is guessed. However, I can't get it to fill in the astericks or to acknowledge when you've guessed it...soem help would be appreciated...thanks in advance. ao5431 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Guessing Game</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <script type="text/javascript"> /* <![CDATA[ */ var mysteryWord = "suspicious"; function checkGuess() { if (document.forms[0].letter.value != "") { var progress = document.forms[0].mysteryWord.value; var guess = document.forms[0].letter.value; document.forms[0].letter.value = guess; mysteryWordArray = mysteryWord.split(" "); var progressArray = progress.split(""); for (var i=0; i<mysteryWord.length; ++i) { var curLetter = mysteryWordArray[i]; if (curLetter == guess) progressArray[i] = guess; } progress = progressArray.join(""); if (progress == mysteryWord) document.forms[0].mysteryWord.value = "You guessed correctly! The mystery word is '" + progress + "'."; else document.forms[0].mysteryWord.value = progress; } else window.alert("You must enter a letter!"); } /* ]]> */ </script> </head> <body> <h1>Guessing Game</h1><hr /> <form action="" method="get" enctype="application/x-www-form-urlencoded"> <p>Mystery word: <input type="text" name="mysteryWord" value="**********" size="100" readonly="readonly" style="border: 0" /></p> <p>Enter a letter and click the Submit Letter button.</p> <p><input type="text" name="letter" size="2" /> <input type="button" value="Submit Letter" onclick="checkGuess()" /></p> </form><hr /> </body> </html> Ok so i want to work on an EASY basic game. As simple as Guess what number... But there are some twist... Ok So here is my example... (HTML, i know this.)I'm Guessing a number 1-99. What is it? (java) Lets say its 66 and they guess 53, have the text rusult be in a pop up window be: Too low! (java) Lets say they guess 78, have the text rusult be in a pop up window be: Too high! (java) Lets say they guess 100+, have the text rusult be in a pop up window be: Out of range! (java)But lets say they guess 66, have a text result be in a pop up window be: You've won! (java) I want a text field where you can enter your answer, and it will do the actions above. Can anyone code this? Thanks for reading! This is a simple basic game i want to make. Its a "What Am I" Riddle... The questions is (In HTML which i already know): I'm as light as a feather but no man can hold me for long. What am I? the answer is: Your Breath. (This is where the JAVASCRIPT comes in) Lets say they guess a rock, have a pop up say: Wrong Answer. Please try again. Lets say they guess Your breath -OR- Breath, have a pop up say: Correct! I want a text field where you can enter your answer, and if they choose ANYTHING but the 2 correct answers above, it will display please try again. Can anyone code this please? Thanks for reading. Dear Experts I want textbox1 to accept only numeric data as 55,65,698.00 Is there any easy way to validate textbox1 with javascript? Please help Dear Experts I have following codes Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="language" content="english"> <meta http-equiv="Content-Style-Type" content="text/css"> <title>Numeric Textbox Sample</title> <style type="text/css"> #box1 {width:200px;height:170px;border:1px solid green;background:#e3eeff;padding-top:20px;} .button {width:100px;margin-top:0px;} body { margin:0; margin-top:100px; } </style> <script language="javascript"> function NumericDotOnly() { var key = window.event.keyCode; if (((key >47) && (key <58)) || (key==46)) window.event.returnValue = true; else window.event.returnValue = false; } function formatCurrency(num) { num = num.toString().replace(/\$|\,/g,''); if(isNaN(num)) num = "0"; sign = (num == (num = Math.abs(num))); num = Math.floor(num*100+0.50000000001); cents = num%100; num = Math.floor(num/100).toString(); if(cents<10) cents = "0" + cents; for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3)); return (((sign)?'':'-') + num + '.' + cents); } </script> </head> <body onload="form2.text1.focus()" > <center> <p>I need following format<br> 99,999,999.99<br> </p> <div id="box1"> <form name=form2> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr><td>Amount</td> <td><input type=text name=text1 size=15 value="" onkeypress="NumericDotOnly ()";onblur="formatCurrency(this.value)"> </td></tr> <tr><td>Tax</td> <td><input type=text name=text2 size=15 value="" onkeypress="NumericDotOnly()";onblur="formatCurrency(this.value)"></td></tr> <tr><td>Result</td><td><input type=text name=text3 size=15 value="" disabled></td></tr> </table> <hr> <input class="button" type=button name=command1 value="Plus" onclick="form2.text3.value=parseFloat(form2.text1.value)+parseFloat(form2.text2.value)"><br> <input class="button" type=button name=command8 value="Focus" onclick="form2.text1.select()";"form2.text1.focus()"><br> <input class="button" type=reset name=command9 value="Reset"> </form> </div> </center> </body> </html> Please help me to apply following format 99,999,999.99 Thanks in advance Shouldn't this work? It's letting the form submit to the next page when I add in this if statement: Code: var first = document.forms["contact1"].elements["name"].value; else if (!preg_match("/^[a-z]$/i", first)) { alert("Please enter only letters for your first name"); return false; } Hi guys, This has been asked before, and i've seen many of the previous posts. And tried for hours. But finally i've broken and have to ask for help. What am I doing wrong here? Can someone please explain? Code: var u=document.forms["lead"]["name"].value; var v=document.forms["lead"]["city"].value; var x=document.forms["lead"]["country"].value; var y=document.forms["lead"]["mobile"].value; var z=document.forms["lead"]["email"].value; if (u==null || u=="") { alert("Please enter your first name."); return false; } if (v==null || v=="") { alert("Please enter your city."); return false; } if (isNaN(lead.y.value)) { alert("bloody work!"); return false; } if (x=="Argentina" && y.length < 11) { alert("Please enter a valid Argentinian phone number."); return false; } Thanks in advance. Utilising "Search" what resides at: http://www.codingforums.com/showthread.php?t=6441 appears to be closest to my problem but does not solve it. I want to use HTML Input text boxes for processing within nested functions and with the results output back to the HTML table. The code contains the HTML and Javascript. As the code stands data is reported back to the HTML table because the wanted functions have been commented out. Within the code is a note regarding the above. If I try to engage the functions add() or take() I have "NaN" returned. I have attempted to use x=Number(yy), x=parseInt(yy), but to no avail. [code]<html > <head> </head> <body> <form id="myself"> <table border="1" bgcolor="lightblue"> <tr height="25px"> <td id="ad" width="25px"></td> <td id="sb" width="25px"></td> </tr> <tr height="25px"> <td><input id="lt" type="text" value="" onChange="calc();" style="width:20px"></td> <td><input id="rt" type="text" value="" onChange="calc();" style="width:20px"></td> </tr> </table> </form> <script language="javascript"> var mm; var nn; var tot; var subt; function calc(){ var n1=document.getElementById("lt").value; var n2=document.getElementById("rt").value; var nn; var mm; nn=Number(n1); mm=Number(n2); tot=mm+nn; // comment these lines out and ad.innerHTML=tot; // activate the functions subt=Math.abs(nn-mm); // sb.innerHTML=subt; // mm and nn need to passed to the functions //add(); //take(); } function add(){ tot=mm+nn; ad.innerHTML=tot; } function take(){ subt=Math.abs(nn-mm); sb.innerHTML=subt; } </script> </body> </html> [icode] I would like to fill a text field using both text and variables.. i.e. it would say x+2, so i would write.. (if 2 were a given variable) form.form1.value = "x+" 2 ??? (I know that isn't correct, I'm just wondering how I would go about this..) First off, I would like to thank everyone who has offered their help so far in my little self-appointed project dealing with astral body locations. I finally have the script working the way it was intended to and am looking at cleaning it up at this point. One of the things I would like to do in cleaning it up is change the way values are inputed when converting from Polar Coordinates to Cartesian Coordinates. The script is currently set up such that Right Accension is input in three fields identified as Hours, Minutes and Seconds. By the same token, the Declination Angle is input through three fields identified as Degrees, Minutes and Seconds. What I would like to do at this point is convert each set of three input fields to a single input field and allow the user to input the values as; Right Accension = 13:23:15.2 Declination Angle = 22:17:33 I understand that these would be inputed as String values and am familiar enough with the Split feature to extract the individual pieces of string (in this instance they would be 13, 23, 15.2 and 22, 17 and 33). What I am not familiar with, however, is converting those string values into numbers. I have done a bit of research into it and haven't really found anything that makes sense to me just yet, so if anyone can offer a bit of guidance, I am all ears. Not looking for anyone to specifically write the code for me, but if one of you fine folks could point me in the right direction as far as tutorials go, I would be thankful. GW Hello experts, I have inserted the easy slider code into my web page to make a sliding gallery. I attempted to modify the code so that numeric navigation AND arrow navigation (next, previous) could toggle slides BUT I can't see the number navigation in IE6. Every other browser I have tested (mac Safari, Firefox, and Google Chrome as well as IE7,8) work perfectly. Since I modified the original, I assume the error is in my javascript code OR in my CSS. Please help. I wouldn't ask if I wasn't at the end of my rope! Here is the Javascript: Code: /* * Easy Slider 1.7 - jQuery plugin * written by Alen Grakalic * http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding * * Copyright (c) 2009 Alen Grakalic (http://cssglobe.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * Built for jQuery library * http://jquery.com * */ (function($) { $.fn.easySlider = function(options){ // default configuration properties var defaults = { prevId: 'prevBtn', prevText: 'Previous', nextId: 'nextBtn', nextText: 'Next', controlsShow: true, controlsBefo '', controlsAfter: '', controlsFade: true, firstId: 'firstBtn', firstText: 'First', firstShow: false, lastId: 'lastBtn', lastText: 'Last', lastShow: false, vertical: false, speed: 900, auto: false, pause: 3000, continuous: false, numeric: false, numericId: 'controls' }; var options = $.extend(defaults, options); this.each(function() { var obj = $(this); var s = $("li", obj).length; var w = $("li", obj).width(); var h = $("li", obj).height(); var clickable = true; obj.width(w); obj.height(h); obj.css("overflow","hidden"); var ts = s-1; var t = 0; $("ul", obj).css('width',s*w); if(options.continuous){ $("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px")); $("ul", obj).append($("ul li:nth-child(2)", obj).clone()); $("ul", obj).css('width',(s+1)*w); }; if(!options.vertical) $("li", obj).css('float','left'); if(options.controlsShow){ var html = options.controlsBefore; if(options.numeric){ html += '<ol id="'+ options.numericId +'"></ol>' if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>'; html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>'; html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>'; if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>'; }; html += options.controlsAfter; $(obj).after(html); }; for(var i=0;i<s;i++){ $(document.createElement("li")) .attr('id',options.numericId + (i+1)) .html('<a rel='+ i +' href=\"javascript:void(0);\">'+ (i+1) +'</a>') .appendTo($("#"+ options.numericId)) .click(function(){ animate($("a",$(this)).attr('rel'),true); }); $("a","#"+options.nextId).click(function(){ animate("next",true); }); $("a","#"+options.prevId).click(function(){ animate("prev",true); }); $("a","#"+options.firstId).click(function(){ animate("first",true); }); $("a","#"+options.lastId).click(function(){ animate("last",true); }); }; function setCurrent(i){ i = parseInt(i)+1; $("li", "#" + options.numericId).removeClass("current"); $("li#" + options.numericId + i).addClass("current"); }; function adjust(){ if(t>ts) t=0; if(t<0) t=ts; if(!options.vertical) { $("ul",obj).css("margin-left",(t*w*-1)); } else { $("ul",obj).css("margin-left",(t*h*-1)); } clickable = true; if(options.numeric) setCurrent(t); }; function animate(dir,clicked){ if (clickable){ clickable = false; var ot = t; switch(dir){ case "next": t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1; break; case "prev": t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1; break; case "first": t = 0; break; case "last": t = ts; break; default: t = parseInt(dir); break; }; var diff = Math.abs(ot-t); var speed = diff*options.speed; if(!options.vertical) { p = (t*w*-1); $("ul",obj).animate( { marginLeft: p }, { queue:false, duration:speed, complete:adjust } ); } else { p = (t*h*-1); $("ul",obj).animate( { marginTop: p }, { queue:false, duration:speed, complete:adjust } ); }; if(!options.continuous && options.controlsFade){ if(t==ts){ $("a","#"+options.nextId).hide(); $("a","#"+options.lastId).hide(); } else { $("a","#"+options.nextId).show(); $("a","#"+options.lastId).show(); }; if(t==0){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); } else { $("a","#"+options.prevId).show(); $("a","#"+options.firstId).show(); }; }; if(clicked) clearTimeout(timeout); if(options.auto && dir=="next" && !clicked){; timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); }; }; }; // init var timeout; if(options.auto){; timeout = setTimeout(function(){ animate("next",false); },options.pause); }; if(options.numeric) setCurrent(0); if(!options.continuous && options.controlsFade){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); }; }); }; })(jQuery); and here is my CSS: Code: #photos{ background-color: #453F33; width: 875px; height: 400px; margin-top: -5px; position: relative; } #slider{ padding-top:50px; margin-left: 180px; } /* image replacement */ .graphic, #prevBtn, #nextBtn, #slider1prev, #slider1next{ margin:0; padding:0; display:block; overflow:hidden; text-indent:-8000px; } #content{ position:relative; } /* Easy Slider */ #slider ul, #slider li, #slider2 ul, #slider2 li{ margin:0; padding:0; list-style:none; } #slider2{margin-top:1em;} #slider li, #slider2 li{ width:500px; height:312px; overflow:hidden; } #prevBtn, #nextBtn, #slider1next, #slider1prev{ display:block; position:absolute; top:170px; left: 40px; } #nextBtn, #slider1next{ left:780px; } #prevBtn a, #nextBtn a, #slider1next a, #slider1prev a{ display:block; position:relative; width:60px; height:77px; background:url(../images/btn_prev.jpg) no-repeat 0 0; } #nextBtn a, #slider1next a{ background:url(../images/btn_next.jpg) no-repeat 0 0; } /* numeric controls */ ol#controls{ margin:1em 0; padding:0; height:28px; margin-left: 650px; } ol#controls li{ margin:0 10px 0 0; padding:0; float:left; list-style:none; height:28px; line-height:28px; display: inline; } ol#controls li a{ float:left; height:28px; line-height:28px; background:#A6000E; color: #FFF; padding:0 10px; text-decoration:none; margin-top: -360px; } ol#controls li.current a{ background:#A1DFC6; color:#fff; } ol#controls li a:focus, #prevBtn a:focus, #nextBtn a:focus{ outline:none; } #slider li span { display: block; width: inherit; height:30px; margin-top: -317px; color: #000; padding-top: 10px; padding-left: 5px; overflow:hidden; overflow-y: hidden; overflow-x: hidden; filter:alpha(opacity=70); -moz-opacity:0.7; -khtml-opacity: 0.7; opacity: 0.7; background-color: #B1AA9A; } And you can view my site in the wild at www.ibikeseoul.com I am finishing up my Form page, and totally forgot to have a numeric only field. So I added it and I can't get it to work. I also am having issues throwing an error when you don't select at least one topping. And are these lines correct? Code: document.cookie = "toppings=" + encodeURIComponent(document.getElementsByName("toppings[]").value); Code: document.cookie = "extra=" + encodeURIComponent(extra); Here is a link to the page hosted on my dropbox http://dl.dropbox.com/u/49211616/dw/...orderPage.html Javascript: Code: function validateOrder () { var crustSelection = document.orderForm.crust.value; var crustPrice; //Adds $1 for Deep DishParmesagn, and Sourdough var count = 0; //Amount of Toppings Selected var choice = ""; //Toppings Selected list var x = ""; //Don't need for the Cookie var extra = 0; //extra charge for toppings over 3 try{ var error = ""; // Initialize Var to store the error messages. if(document.getElementById("delivery").checked != true && document.getElementById("takeout").checked != true) { error=error+"Order Type is required.\n" } if(document.getElementById("fname").value == "") { error = error + "First Name is required.\n"; } if(document.getElementById("lname").value == "") { error = error + "Last Name is required.\n"; } if(document.getElementById("address").value == "") { error = error + "Street address is required.\n"; } if (isNaN(document.getElementById("quantity"))) { error = error + "Enter Pizza Quantity in Numbers Only.\n"; } if(document.getElementById("crust").value == "") { error = error + "Crust Type is required.\n"; } if(document.getElementsByName("toppings").value == 0) { error = error + "Select at Least One Topping.\n"; } if(error == "") { // save all the information in the cookie document.cookie = "firstName=" + encodeURIComponent(document.getElementById("fname").value); document.cookie = "lastName=" + encodeURIComponent(document.getElementById("lname").value); document.cookie = "address=" + encodeURIComponent(document.getElementById("address").value); document.cookie = "order=" + encodeURIComponent((document.getElementById("delivery").checked) ? "delivery" : "takeout"); document.cookie = "quantity=" + encodeURIComponent(document.getElementById("quantity").value); document.cookie = "quantity=" + encodeURIComponent(document.getElementById("quantity").value); document.cookie = "crust=" + encodeURIComponent(document.getElementById("crust").value); document.cookie = "toppings=" + encodeURIComponent(document.getElementsByName("toppings[]").value); alert("Order successfully Placed!"); } else { alert(error); } } catch(ex) { alert("An error occurred!.\n" + "Error Name : " + ex.name + "\nError Message : " + ex.message); } for (var i=1; i<11; i++) { x = document.orderForm['toppings' + i].value; if (document.orderForm['toppings' + i].checked) { choice = choice + " " + x ; count ++; } } if (choice.length <= 0) { choice = choice + "NONE"; } if (count > 3) { extra = (count - 3) * 1 } document.cookie = "extra=" + encodeURIComponent(extra); } </script> HTML: Code: <form name = "orderForm" onsubmit="validateOrder()"> <table width="600" border="0"> <tr> <th scope="col" width="400" align="left"><b>First Name</b><br /><input type="text" id="fname" name="fname" size=30> <br /> <br /> <b>Last Name</b><br /> <input type="text" id="lname" name="lname" size=30> <br /> <br /> <b>Street Address</b><br /> <input type="text" id="address" name="address" size=30> <br /> <br /> <input name="orderType" value="delivery" id="delivery" type="radio">Delivery</font> <input name="orderType" value="takeOut" id="takeout" type="radio">Take Out</font></th> <th scope="col" width="200" align="Left"> How Many Pizzas? <input type="text" id="quantity" name="quantity" size=5> <br /> <br /> <select name="crust" id="crust"> <option selected value="false">Select Crust Type</option> <option value="regular">Regular Crust</option> <option value="thin">Thin Crust</option> <option value="deep">Deep Dish</option> <option value="Parmesagn">Parmesagn Cheese</option> <option value="sourdough">Sourdough</option> </select> <br /> <br /> Select at Least One Topping: <br /> <br /> <input name = "toppings1" type = "checkbox" value = "extraCheese"> Extra Cheese<br> <input name = "toppings2" type = "checkbox" value = "sausage"> Sausage<br> <input name = "toppings3" type = "checkbox" value = "pepperoni"> Pepperoni<br> <input name = "toppings4" type = "checkbox" value = "bacon"> Bacon<br> <input name = "toppings5" type = "checkbox" value = "canadianBacon"> Canadian Bacon<br> <input name = "toppings6" type = "checkbox" value = "mushroom"> Mushroom<br> <input name = "toppings7" type = "checkbox" value = "pineapple"> Pineapple<br> <input name = "toppings8" type = "checkbox" value = "onion"> Onion<br> <input name = "toppings9" type = "checkbox" value = "olive"> Olive<br> <input name = "toppings10" type = "checkbox" value = "greenPepper"> Green Pepper<br></th> </tr> </table> <input name="submit" type="submit" value="submit" /><input name="" type="reset" /> </form> Hi.. I am facing identifier starts immediately after numeric literal error in firefox onclick="document.location.href='<%= themeDisplay.getPathMain() %>/portal/ext/asite/assignOrg'"/> can any 1 solve this?? Hi, I want to have a textbox in which only numeric values will be allowed whose maximum limit is 240( 230.99 should be allowed). I am unable to do that. I am able to format the value entered by placing . in proper places and also I have limited upto two decimal places. But the problem is the cursor is not moving left when I have entered a value and I am unable to limit the value upto 240. It is taking any huge number also. Please help. My code is as below :- <html> <head> <script> function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } function format(input){ var num = input.value.replace(/\,/g,''); if(!isNaN(num)){ if(num.indexOf('.') > -1){ num = num.split('.'); if(num[1].length > 2){ num[1] = num[1].substring(0,num[1].length-1); } input.value = num[0]+'.'+num[1]; } else { input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'') }; } else { input.value = ""; } } </script> </head> <body> <label for="time">Files staged in the last -</label> <input name="time" id="time" type = "text" value="24" onkeypress="return isNumberKey(event)" onkeyup="format(this);"/> <span>hours</span> </body> </html> |