JavaScript - If Random Number Equals This, Then Show Text...
Hi, I have been here before and was responded to quickly with professional results, and you guys have managed to bring me back!
Anyway, I am horrible at coding, and I need to know how to write this, basically when the page loads a random number is generated <script type="text/javascript"> window.onload=function() { var random = Math.rand() * (6 + 1); Then later in the page if (random = 1) { document.write("1") //I'm not sure if thats the code to show simple text, but I'm pretty sure it is, correct me if I'm wrong } if (random = 2) { document.write("2") } if (random = 3) { document.write("3") } and so on so forth. I will be changing the numbers in the script to my accord and use of the script, so please use the //notes to mark where and what things is, with a brief explanation, so I don't have to unscramble the code to find out what it is. Thanks fellow nerds! Similar TutorialsThis is quite easy yet hard. I'm trying to apply something in my forums, where a member could post something let's say: "Hi, I am number [random]1, 6[/random]" And what would happen is that, a number from 1 to 6 would be the content, for example, it would be: "Hi, I am number 3" But if you refresh the page, it would still be the same number. Like it won't be randomized again. So how do I make a javascript/html code that would make a one time number randomizer. I need to write something like this: http://justsheri.com/webscripting/wsassignment/1049950/ If you look at the code there is 52 of these <img src = './images/blank1.png' onClick='clickCard("qh",0)'/> where clickcard("numchanges", increments by 1) how is this done? Thanks Danny I can generate a random number between 1 and 9, ( var rand_no = Math.floor( 1 + Math.random() * 9 ); ) but I want to add that random number to a value that is enterred into an inputbox and get a total. How can I do this using Javascript and put the result into a hidden field. I will also need to use that same random number in another place on another form . Thanks I have a function below where every time a question is submitted, it will add a new row in the table with a textbox which allows numbers entry only. My question is that I don't know how to code these features in this function: 1: I want the text box to be between 0 and 100, so if text box contains a number which is above 100, it will automatically change the number to the maximum number which is 100. Does any one know how to code this in my function below in javascript: Code: function insertQuestion(form) { var row = document.createElement("tr"); var cell, input; cell = document.createElement("td"); cell.className = "weight"; input = document.createElement("input"); input.name = "weight_" + qnum; input.onkeypress = "return isNumberKey(event)"; cell.appendChild(input); row.appendChild(cell); } I need help with a code that will generate a random number or integer (from 1-9). Does anybody know of a short random generator without having to import anything? thank you.
I am makeing a dice game and this is how i generate the numbers
Code: var randomnumber1=Math.floor(Math.random()*13) But i have to relaode the page each time to randomize it again. How can i do this with out reloading the page? I am using a button to set the function of. Hi i'm trying to make a unique random number function but i''m stuck in an infinite loop here is what ive been trying below. basically i would like the output to be VolvoSaabBMW in a random order and it should NEVER be VolvoVolvoBMW or anything of the likes, each array item can should only be used once basically. Thanks for any help at all! Code: <html> <body> <script type="text/javascript"> var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; var uniquerand = new Array(); var c = 0; function randno(arrayname) { var i; var b = 0; var randomnumber=Math.floor(Math.random()*arrayname.length); if(c == 1) { while (b<1) { for (i=0;i<uniquerand.length;i++) { if(uniquerand[i] != randomnumber) { document.write(mycars[randomnumber]); uniquerand.push = randomnumber; b = 1; } } } } else { randomnumber=Math.floor(Math.random()*arrayname.length); uniquerand.push = randomnumber; document.write(mycars[randomnumber]); c=1; } } randno(mycars); randno(mycars); randno(mycars); </script> </body> </html> i have a table with a couple random numbers, and i want to click a button that will dynamically regenerate the numbers each time the button is clicked without re-generating the entire table., im using DOM and innerhtml for these random numbers. heres the javascript and html code. so far, it just generates the random numbers when the page loads. i posted this problem a while back, and the answers were great, but they coded the xhtml inside the html file. i'm trying to get the numbers to generate in the table that is formed in the javascript file using innerhtml. i tried to incorporate the solutions without putting the html inside the html file to no avail. var random = Math.floor(Math.random()*40 + 1) //sets variables for random numbers to generate var random2 = Math.floor(Math.random()*40 + 1) var random3 = Math.floor(Math.random()*40 + 1) var random4 = Math.floor(Math.random()*40 + 1) var random5 = Math.floor(Math.random()*40 + 1) var random6 = Math.floor(Math.random()*40 + 1) //create table function makeTable(lotto) document.getElementById("tableSpan").innerHTML = '<table border="1" id="lotto">'; var caption=document.getElementById('lotto').createCaption(); caption.innerHTML="JavaScript Random Numbers"; var x=document.getElementById('lotto').insertRow(0); var cell1=x.insertCell(0); var cell2=x.insertCell(1); var cell3=x.insertCell(2); var cell4=x.insertCell(3); var cell5=x.insertCell(4); var cell6=x.insertCell(5); cell1.innerHTML='<td class = "normal">'+ random +'</td>'; cell2.innerHTML='<td class = "normal">'+ random2 +'</td>'; cell3.innerHTML='<td class = "normal">'+ random3 +'</td>'; cell4.innerHTML='<td class = "normal">'+ random4 +'</td>'; cell5.innerHTML='<td class = "normal">'+ random5 +'</td>'; cell6.innerHTML='<td class = "red">'+ random6 +'</td>'; } heres the HTML file: <body onload="makeTable('lotto');"> <div id="container"> <div id="header"> <h1>Welcome</h1> </div> <div id="content"> <span id="tableSpan"></span> <input type="button" value="Re-generate Numbers" onclick="makeTable('lotto');" /> </div> { Hi, First, I'm a newbie in javascript and I need help to do something with a random numbers. I would like to put the result numbers in the "<td class="style1">#01</td>" section and an image in <td class="style1">img1</td> depending of the result number. Exemple : If the result number is #1 then the image Under the #01 will be an image associated to the number 1". Number 1 = "red circle.jpg", Number2 = "blue square.jpg", etc. Am I clear ? Here is my actual HTML canvas : -------------------------------------- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Result</title> <style type="text/css"> .a1{ position:relative; font-family:Verdana; font-size:20px; color:#888888; } .style1 { text-align: center; } </style> <script language="JavaScript"> /***************************************** * Lottery Picker (By Kurt at kurt.grigg@virgin.net) * Featured on/available at Dynamic Drive DHTML(dynamic html) & JavaScript code library * Modified by DynamicDrive.com for below config options * This notice must stay intact for use. *****************************************/ var totalnumbers=6 //input total numbers to generate var lowerbound=1 //input lower bound for each random number var upperbound=49 //input upper bound for each random number function lotto(){ B=' '; LottoNumbers=new Array(); for (i = 1; i <= totalnumbers; i++) { RandomNumber = Math.round(lowerbound+Math.random()*(upperbound-lowerbound)); for (j = 1; j <= totalnumbers; j) { if (RandomNumber == LottoNumbers[j]) { RandomNumber=Math.round(lowerbound+Math.random()*(upperbound-lowerbound)); j=0; } j++; } LottoNumbers[i]=RandomNumber; } LottoNumbers=LottoNumbers.toString(); X=LottoNumbers.split(','); for (i=0; i < X.length; i++) { X[i]=X[i]+' '; if (X[i].length==2) X[i]='0'+X[i]; } X=X.sort(); for (i=0; i < X.length; i++) { OutPut=B+=X[i]; } if (document.all)document.all.layer1.innerHTML=OutPut; if (document.getElementById)document.getElementById("layer1").innerHTML=OutPut; if (document.layers){ document.layers.layer1.document.open(); document.layers.layer1.document.write("<span style='position:absolute;top:0px;left:0px;font-family:Verdana;font-size:20px;color:#888888;text-align:center'> "+OutPut+"</span>"); document.layers.layer1.document.close(); } T=setTimeout('lotto()',20); //window.status=OutPut; } function StOp(){ setTimeout('clearTimeout(T)',1000); } //--> </script> </head> <body> <table border='0' width=250 style="height: 146px"> <tr valign='middle'> <td align='center'> <form name=form> <input type=button value='Lottery Number Picker' onClick="lotto();StOp()"> </form> <span id=layer1 class=a1>Result</span> </td> </tr> </table> <table style="width: 250px; height: 100px" cellspacing="0" cellpadding="0"> <tr> <td class="style1">#01</td> //result number 1 have to be here <td class="style1">#02</td> //result number 2have to be here <td class="style1">#03</td> //result number 3 have to be here <td class="style1">#04</td> //result number 4 have to be here <td class="style1">#05</td> //result number 5 have to be here <td class="style1">#05</td> //result number 6 have to be here <td style="height: 50px" class="style1">#06</td> </tr> <tr> <td class="style1">img1</td> //associated image of the result number 1 have to be here <td class="style1">img2</td> //associated image of the result number 2 have to be here <td class="style1">img3</td>//associated image of the result number 3 have to be here <td class="style1">img4</td>//associated image of the result number 4 have to be here <td class="style1">img5</td>//associated image of the result number 5 have to be here <td class="style1">img6</td>//associated image of the result number 6 have to be here </tr> </table> </body> </html> -------------------------------------- Thank you very much to helping me to understand how to do it !! Sylvano Reply With Quote 12-22-2014, 05:36 PM #2 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts This is hideously old and indeed crude code. document.all applied to IE4 and document.layers to Netscape 3. <script language="JavaScript"> and document.write() are also long obsolete. As is T=setTimeout('lotto()',20); I would suggest you get hold of a more up-to-date code. Simply rename your images 1.jpg, 2.jpg and so on, and display the appropriate one in its correct position. I'll give you a far better lottery number generator:- Code: <!DOCTYPE html> <head> </head> <body> <script type = "text/javascript"> function mylotto() { var rlts = document.getElementById("results"); rlts.value = ''; // clear results var srtrlts = document.getElementById("sortedresults"); srtrlts.value = ''; // clear results var hmany = document.getElementById("howmany").value; var max = parseInt(document.getElementById("maxnum").value); if (isNaN(max) || max <= hmany) { alert ("You must choose a number greater than " + hmany + " for the maximum number value!"); document.getElementById("maxnum").value = 49; return false; } var numArray = new Array(max); var chosen = new Array(hmany); var uniqueList = new Array(hmany); for (var i = 1; i <= max; i++) { // set up array 1 to max numArray[i-1] = i; } Array.prototype.shuffle = function() { var s = []; while (this.length) s.push(this.splice(Math.random() * this.length, 1)); while (s.length) this.push(s.pop()); return this; } numArray.shuffle(); // shuffle the array for (var i = 0; i < hmany; i++) { // take the first howmany items uniqueList[i] = numArray[i]; } rlts.value = uniqueList.join(" "); srtrlts.value = uniqueList.sort(sortNumber).join(" "); function sortNumber(a,b) { return a - b; } //alert ("The unsorted random numbers a - \n" + uniqueList) //alert ("The sorted unique random numbers a - \n" + uniqueList.sort(sortNumber)); } </script> <p>UNIQUE NUMBERS LOTTERY PICKER</p><br> <form> Select How Many Unique Numbers <select id="howmany"> <option value=1>1</option> <option value=2>2</option> <option value=3>3</option> <option value=4>4</option> <option value=5>5</option> <option value=6 selected>6</option> <option value=7>7</option> <option value=8>8</option> <option value=9>9</option> <option value=10>10</option> </select> <br> Enter the Maximum Number Value  <input type="text" id = "maxnum" value="49" size="2"><br><br> <input type="button" value="Here we go!" onclick="mylotto()"> <br><br> Unsorted Results:- <input type = "text" id = "results" size = "60"><br> Sorted Results:-     <input type = "text" id = "sortedresults" size = "60"> </form> </body> </html> Quizmaster: In which river did John the Baptist baptise Jesus? Contestant: The Amazon How would I generate a random number between 0 and 470 at multiples of 10 including 0 and 470?
Hi, I have a 'Register' page on my site. When someone registers to my website, I would like to make it necessary to have a div box which generates a random number/letter, which is linked to a text field where the user has to match the generated output. I've been sitting here wondering which would be the best route to take regarding completing this. I was thinking about using charAt() method. Could anybody please possibly give me some tips for generating random letter/numbers? Possibly would I create a string containing "ABCDE....Z0123456789", then use the charAt method to find a character at a certain index position? If so, would I need create something which generates a random index position? Any help would be fantastic, thank-you. hi all, i was hoping somebody could help me out. i'm trying to write a code that generates a random number between 1 and 9999 on page load, concatenates it with "pwn" at the start, and adds it to a disabled form text input box. this is the code i have below, but it's not working at all. any help would be greatly appreciated. in the head section Code: <script type="text/javascript"> function createcode() { var randomnumber = Math.floor(Math.random()*10000); var homecode = 'pwn' + randomnumber; } </script> my body tag Code: <body onload="createcode()"> and the form field itself Code: <input type="text" name="homename" id="homename" disabled="disabled" /> <script type="text/javascript"> document.getElementByID("homename").value = homecode; document.write(homecode); </script> thanks in advance. Hey guys, I scripted a javascript guessing game and I am not sure how I can configure the random number generator to only generate one number and then stop. Here is my code: Code: <html> <head> <title>Guess it up! </title> </head> <body> <center> <BODY onLoad="GenerateNumber()"> <b><font size="5" ><u><b>Guess it up!<br></b></u> <br > <font size="3"> This is out of: <br> <input id="DefaultNumber" name="DefaultNumber" type="text" size=3><br> Type in your guess: <br> <input id="HisGuess" name="HisGuess" type="text" size=3> <p> <input name="StartButton" type="button" value="Guess" onclick="StartGame()"> </p> <script type="text/javascript"> function GenerateNumber() { var TheRightGuess = Math.round(Math.random() * (document.getElementById("DefaultNumber").value))+1; //Makes the randomly generated right guess. The "+1" makes it 1-5 instead of 0-4. } function StartGame() { var TheRightGuess = Math.round(Math.random() * (document.getElementById("DefaultNumber").value))+1; //Makes the randomly generated right guess. The "+1" makes it 1-5 instead of 0-4. var HisGuess = parseInt(document.getElementById("HisGuess").value);//his guess var DefaultNumber = parseInt(document.getElementById("DefaultNumber").value);//number that they want to guess in. //NUMERIC TEST STARTS HERE if (HisGuess != parseInt(HisGuess) || (DefaultNumber != parseInt(DefaultNumber))) { alert("Please enter numbers only.") } //NUMERIC TEST ENDS HERE if (DefaultNumber <= 0) //Fixed bug:Guessing in zero. { alert("You can't guess in zero!?") } else if (DefaultNumber === 1 && HisGuess === 1 || TheRightGuess == HisGuess && DefaultNumber != 1)//testing if they guessed in 1 and guessed 1. { alert("You got the number!") } else if (HisGuess > DefaultNumber)//if guess is higher then what they guess in. { alert("You can only guess below " + DefaultNumber + ".") } else if (HisGuess != TheRightGuess && HisGuess <= DefaultNumber && DefaultNumber != 1 || HisGuess == 0)//fixed bug: you can't guess 0. { alert("Guess again!") } } </script> </body> </html> Thanks, Fizz Hello, There isa demo below. I have a form and select menus. I am posting it ajax post method and loading the same page with load method as you see in codes. There is a random number genarator. I want to change this random number once a click submit. If i do not load the same page this number does not change. Therefore I use both post and load methods like in demo. However when i do like this there is a problem which is random number have been generated twice somtimes. If you click submit button successively you will see that the number on left top corner sometimes changes twice a click. Why it is so and how can i correct it. Thanks in advance and sorry for my bad English Demo: http://fcbk.imeee.org/test.php test.php PHP Code: <?php print_r($_POST['soru']); echo rand(5, 15); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <link href="style.css" media="screen" rel="Stylesheet" type="text/css"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#submit").click(function(event){ $.post( "test.php", $("#sorular").serializeArray(), function(data) { $('#results').html(data); } ); $(".arkadaslar").load("test.php?r=1"); }); }); </script> </head> <body> <?php if(!$_POST):?> <?php if($_GET['r']!=1):?> <ul class="arkadaslar"> <?php endif;?> <form name="ss" id="sorular"> <?php for($i = 1; $i <= 4; $i++):?> <table width="100%" border="0" align="left" cellpadding="0" cellspacing="0"> <tr> <td width="70%" align="left" valign="top"></td> <td width="30%" align="left" valign="top"> <label> <select name="soru[]" size="1" id="select"> <option>Give point</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> </label> </td> </tr> </table><br /><br /> <?php endfor; ?> <input id="submit" type="button" value="Submit"> </form> </ul> <?php endif;?> <p><tt id="results"> </tt></p> </body> </html> How would I go about creating a random number between 1-50 that COULD include whole numbers, decimals to the tenth, hundredth and the thousandth place? Ex) 2.145, 3, 5.8, 41.002, 10.12, 7, 18.023, 33.2 Also, if the only way to do it is to put trailing zeros to the thousandth place that's fine as well ex) 2.145, 3.00, 5.800, 41.002, 10.120, 7.00, 18.023, 33.200 I've looked everywhere for a random number generator which doesn't repeat. Tried loads and none have seemed to work. I'm making a quiz, 5 questions so far. This button, in html, generates the next random Q: Code: <input type="button" value="Next (random)" name="B0" onClick="rangen();generatequestions();qnum()"><br><br> Lower down in the javascript (in the body), here is the rangen() function: Code: function rangen(){ whichone=Math.floor(Math.random()*5) } But I need a random generator which fires them off only once. For reference, here is the next bit (not so important): Code: var whichone=1; var q=1; var tempmn=document.instantquiz.thequestion function generatequestions(){ if (q>0) q=q++ if (loop>0) loop=0 document.instantquiz.theresponse.selectedIndex=0 if (!document.instantquiz.cmode.checked||whichone>=total+1||whichone<=0) document.instantquiz.thesolution.value='' if (whichone>=total+1) tempmn.value="End of quiz" else{ tempmn.value=whichone+")"+question[whichone]+"\n\n"+"a)"+eval('choice'+whichone+'[1]')+"\n"+"b)"+eval('choice'+whichone+'[2]' )+"\n"+"c)"+eval('choice'+whichone+'[3]')+"\n"+"d)"+eval('choice'+whichone+'[4]') if (document.instantquiz.cmode.checked) document.instantquiz.thesolution.value=solution[whichone] } } Anyone have suggestions for a non-repeating random number gen which will work? Even the one now seems to have some slight error associated with it. The one's ive tried so far haven't worked.. Hello, I have a coding project that I am working on, and I have gotten stumped. Basically win the page loads I want to show random numbers in two textboxes or labels, I would prefer labels. What this is going to be used for is...it is suppose to be for a math learning tool for first, second and third graders. Also another question is that I am suppose to give them digits based upon their grade level. So for first grade 1+1=2 second grade 2 digits, third 3 digits but can have a four digit answer. Plus it can't have negative numbers, nor have remainders for division. Also I don't want to use buttons if at all possible I want the numbers to load automatically. I know this is a loaded question and I have worked tons on it, for me its trying to get the last few things to work together that's giving me trouble. If you would like to see sections of my code please ask cause it is tons as of right now. Thanks for your help. Hello, I need help creating a function in javascript that produces random numbers generated from a normal curve distribution with a mean and standard deviation that I can specify (and easily change). I would like only whole numbers and the ability to set reasonable maximum and minimums. Thanks, Adrian Hello all! I'm completely new here so I hope I'm doing this right and posting this in the appropriate subforums - if not, my apologies! Anyways, on to my actual problem. I am using the following script on a website to display a different image every time one visits/refreshes. The problem is, sometimes, instead of one of the images I have defined, it will come up with a broken image. I have tried to find something about this kind of thing in tutorials and such, but I have been unable to find anything on the subject. So - here's the code I'm using - Code: <script type="text/javascript"> <!-- var rand=Math.round(Math.random()*6); var img=new Array(6); img[0]="layout/bottomright/00.gif"; img[1]="layout/bottomright/01.gif"; img[2]="layout/bottomright/02.gif"; img[3]="layout/bottomright/03.gif"; img[4]="layout/bottomright/04.gif"; img[5]="layout/bottomright/05.gif"; document.write("<img src=\"" + img[rand] + "\" />"); //--> </script> Because I have extremely limited knowledge of JavaScript, I am not sure where the problem lies. (I made this script following a tutorial a long time ago and it worked completely fine then - I only changed the number in the "var rand" line to match the number of images I'm using this time, and the issue was present right from the start. I changed "var img" a lot in attempts to fix the issue - like I said, little knowledge, so I was just trying things - but it made no difference.) A more savvy friend of mine pointed out that the generator throws an "undefined" number occasionally, but she didn't know why. So... any help? I hope it's not too complex an issue. Thanks in advance! |