johnnyg24 Posted April 24, 2009 Share Posted April 24, 2009 I am submitting a form with the standard <input type="submit" name="patternSubmit" value="Search" />. I need to also pass a variable, "randomnumber", and it's value that I create in a function. The function creates a random number from 1 to a million: function randomNum() {var randomnumber=Math.floor(Math.random()*1000000);} all of the values of this form will be submitted to a program that will create an xml. The program will then use "randomnumber" as the file name of the xml. My question is how do I submit a form and all of its values plus the "randomnumber" value using JavaScript? Link to comment Share on other sites More sharing options...
jesh Posted April 24, 2009 Share Posted April 24, 2009 You can add a hidden input that stores your random number and populate it on page load:HTML: <input type="hidden" id="randomnumber" name="randomnumber" /> java script: function randomNum() {document.getElementById("randomnumber").value = Math.floor(Math.random()*1000000);}window.onload=randomNum; EDIT: Also, as far as I am aware, your random number algorithm will produce numbers between 0 and 999,999 rather than 1 and 1,000,000. Link to comment Share on other sites More sharing options...
justsomeguy Posted April 27, 2009 Share Posted April 27, 2009 Math.random goes from 0 to 1, so if it's 1 then the result will be 1000000. So the range is 0 to 1000000. Link to comment Share on other sites More sharing options...
jesh Posted April 27, 2009 Share Posted April 27, 2009 I was always under the impression that Math.random goes from 0 to <1. The following test, run ten times to get 100,000,000 random numbers, never once produces a 1 (which would attempt to increment an element in the array that doesn't exist): <html><body><script type="text/javascript">var output = [0,0,0,0,0];for(var i = 0; i < 10000000; i++){ output[Math.floor(Math.random()*output.length)]++;}document.write(output);</script></body></html> Link to comment Share on other sites More sharing options...
Ingolme Posted April 27, 2009 Share Posted April 27, 2009 EditedApparently, I was mistaken as to the specifications of the random method were in Javascript. Link to comment Share on other sites More sharing options...
justsomeguy Posted April 27, 2009 Share Posted April 27, 2009 I was always under the impression that Math.random goes from 0 to <1.Actually, that's correct.Returns a pseudo-random number in the range [0,1) — that is, between 0 (inclusive) and 1 (exclusive).If you want a number from 1 to 10, you would do this:var v = Math.floor(Math.random() * 10) + 1; Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.