www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 23

Thread: Random values to Database

  1. #1
    Join Date
    Nov 2011
    Posts
    31

    Random values to Database

    Hi everyone,

    I new to javascript. I want to generate 50 random numbers between 1 and 500 and store in a database. Is there a way to do it using javascript and SQL?

    Regards,

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,259

    Lightbulb

    You can create the random numbers easily,
    but there is not a way to save them using JS only.
    Code:
    <!DOC HTML>
    <html>
    <head>
    <title> Untitled </title>
    <script type="text/javascript">
    function rndNumbers() {
      var tarr = [];
      for (var i=0; i<50; ++i) {
        if ((i % 10) == 0) { tarr.push('<br>'); }
        tarr.push(Math.floor(Math.random()*500)+1);
      }
      document.getElementById('fiftyNumbers').innerHTML = tarr.join(',');
    }
    </script>
    
    </head>
    <body>
    <button onclick="rndNumbers()">Generate</button>
    <div id="fiftyNumbers"></div>
    </body>
    </html>

  3. #3
    Join Date
    Nov 2011
    Posts
    31
    Hello,

    Thanks!
    How can I change the script so that the generated numbers will be in a form field?

    Regards
    RESA

  4. #4
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    change
    HTML Code:
    <div id="fiftyNumbers"></div>
    to
    HTML Code:
    <textarea cols="60" rows="40" id="fiftyNumbers"></textarea>
    and change this line
    Code:
     document.getElementById('fiftyNumbers').innerHTML
    to
    Code:
     document.getElementById('fiftyNumbers').value
    Then the form field element will be populated with the result.
    We all have baggage to carry in life, unfortunately for me I always get the trolley with the wonky wheel...
    Code:
    Youre = {
          STILL_not_getting_it:function(){
               alert("YOU, the original poster / thread starter NEED to POST the code and NOT a LINK.");
          },
          MissingThePoint:function(msg){
                alert("You're missing the point. " + msg);
          }
    }
    Youre.STILL_not_getting_it();

  5. #5
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,259
    And to complete the process, change
    Code:
        if ((i &#37; 10) == 0) { tarr.push('<br>'); }
    to
    Code:
        if ((i % 10) == 0) { tarr.push('\n'); }

  6. #6
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,252
    A method to choose randomly 50 numbers without repetitions and to send this numbers to a php file for storage in a data base...
    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="fr">
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta http-equiv="cache-control" content="no-cache">
    <meta name="generator" content="PSPad editor, www.pspad.com">
    <title>Random Values</title>
    <style type="text/css">
    body {margin:0;padding:0;font-family:Georgia;text-align:center;}
    #pge {display:block;width:500px;margin:3px auto;}
    p.snd {cursor:pointer;color:#909;}
    </style>
    </head>
    <body>
    	<div id="pge">
    	<p id="rsp"></p>
    	<p class="snd" onclick="snd()">Send to data base !</p>
    </div>
    <script type="text/javascript">
    // With for example 500 items (from 01 to 500) 
    	var nbrItm=500,nbrTrt=0,nbrAtr=50;// Total number of item, number of pulled items and number to be pulled
    	var itmLst='',itmObj={} // array and object with pulled items 
    	do {var k=1+Math.floor(Math.random()*(nbrItm-nbrTrt));// choose of a rank among the remaining items
    		// Reduce k for every remainig item to take the kth, when k is null
    		for (var i=1;;i++) if (typeof(itmObj[i])!='number' && (--k)==0){
    			itmObj[i]=1;itmLst+=','+i;break;}
    		nbrTrt++} 
    	while (nbrTrt!=nbrAtr);
    	itmLst=itmLst.substr(1).split(/,/g).sort(function(a,b){return a-b;}).join(', ');
    	document.getElementById('rsp').innerHTML=itmLst;
    
    	function snd(){var s;
    	// Supression &#233;ventuelle du script pr&#233;c&#233;dent
    	  s=document.getElementsByTagName("script");
    	  for (i=0;i<s.length;i++)
    			if (s[i] && s[i].getAttribute("src")!=null && s[i].getAttribute("src").indexOf('storeData.php')!=-1)
    	    	s[i].parentNode.removeChild(s[i]);
    	s=document.createElement('script');
    		s.type = 'text/javascript';
    		s.src = 'storeData.php?lst='+itmLst;
    		document.getElementsByTagName("head")[0].appendChild(s);
    	}
    </script>
    </body>
    </html>
    The php script (storeData.php) is very ligth...
    PHP Code:
    <?php
    header
    ("Cache-Control: no-cache, must-revalidate");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Content-Type:text/javascript;charset=utf-8");
     
        if (!empty(
    $_GET)) {
            
    $lst=$_GET["lst"];
        
    //    insert the list in the data base 
        

            exit(
    "alert('List successfully receveid : ".$lst."');");
    ?>
    It works as on this test page.
    Last edited by 007Julien; 11-26-2011 at 05:36 PM.

  7. #7
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    You should see this one by VWP http://www.webdeveloper.com/forum/sh...d.php?t=252615 which does just that but will pick losers rather than the common pick winners method and leaves a list of winners through selection of losing tickets / seats.
    We all have baggage to carry in life, unfortunately for me I always get the trolley with the wonky wheel...
    Code:
    Youre = {
          STILL_not_getting_it:function(){
               alert("YOU, the original poster / thread starter NEED to POST the code and NOT a LINK.");
          },
          MissingThePoint:function(msg){
                alert("You're missing the point. " + msg);
          }
    }
    Youre.STILL_not_getting_it();

  8. #8
    Join Date
    Nov 2011
    Posts
    31
    Hello.

    Thanks for alll your answers! But now its more complicated!
    I have a form with 2 fields: sample_size and sample_nums.
    The user enters a number in the field sample_size (example: 90) and if the field sample nums is empty the page will fill the sample_num with 40 not repeated random numbers (Example: 5,67,32,78,90, ...).
    This depends on the number entered from the user:

    From 1 to 8: 8 numbers
    From 8 to 15: 15 numbers
    From 16 to 25: 25 numbers
    From 26 to 50: 25 numbers
    From 51 to 90: 40 numbers
    From 91 to 150: 60 numbers
    From 151 to 280: 105 numbers
    From 281 to 500: 170 numbers
    From 501 to 1200: 300 numbers
    From 1201 to 3200: 200 numbers

    How can I do this in javascript?

    Best regards,
    RESA

  9. #9
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,259
    Use the previous examples and make an attempt at doing your own homework first!

  10. #10
    Join Date
    Nov 2011
    Posts
    31
    Sorry JMRKER. I'm new in programming.

    I have write this function:
    function randon_sample() {
    units = document.getElementById('batch_size').value);
    sample = document.getElementById('batch_smp').value);
    var smp = [];
    if ( sample =='0'&& units<=8 {
    for (var i=0; i<8; ++i) {
    if ((i % 10) == 0) { tarr.push('\n'); }
    smp.push(Math.floor(Math.random()*units)+1);
    }
    }
    if ( sample =='0'&& (units>8 && units<=15) {
    for (var i=0; i<8; ++i) {
    if ((i % 10) == 0) { tarr.push('\n'); }
    smp.push(Math.floor(Math.random()*units)+1);
    }
    }
    if ( sample =='0'&& (units>15 && units<=25) {
    for (var i=0; i<8; ++i) {
    if ((i % 10) == 0) { tarr.push('\n'); }
    smp.push(Math.floor(Math.random()*units)+1);
    }
    }
    document.getElementById('batch_smp').value = smp.join(',');

    }

    But its not working. Can you please tell me were I'm doing wrong?

    Thanks!
    RESA

  11. #11
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,259

    Lightbulb

    I would recommend a couple of things concerning your submissions:
    1. Check the error console (especially if using FF or Chrome browsers) to find the obvious syntax errors.
    2. Enclose you script between [ code] and [ /code] tags (without the spaces)
    to make it easier for forum members to read, copy, test and comment upon.
    Code:
    <!DOC HTML>
    <html>
    <head>
    <title> Untitled </title>
    <script type="text/javascript">
    // From: http://www.webdeveloper.com/forum/showthread.php?p=1181976#post1181976
    
    //<![CDATA[
    var smp = [];
    
    function fill_smp(units) {
      smp = [];
      for (var i=0; i<units; ++i) { smp.push(i+1); }
      smp = smp.sort(randOrd);
    }
    
    function randOrd() {
      return (Math.round(Math.random())-0.5);
    }
    
    function padLeft(value,size) {  // to make pretty
      value = value.toString();
      while (value.length < size) { value = ' '+value; }
      return value;
    }
    
    function randon_sample() {
      units = document.getElementById('batch_size').value;
    
      if ( units>1200 && units<=3200 ) { fill_smp(200); }
      if ( units>500 && units<=1200 ) { fill_smp(300); }
      if ( units>280 && units<=500 ) { fill_smp(170); }
      if ( units>150 && units<=280 ) { fill_smp(105); }
      if ( units>90 && units<=150 ) { fill_smp(60); }
      if ( units>50 && units<=90 ) { fill_smp(40); }
      if ( units>25 && units<=50 ) { fill_smp(25); }
      if ( units>15 && units<=25 ) { fill_smp(25); }
      if ( units>8 && units<=15 ) { fill_smp(15); }
      if ( units>0 && units<=8 ) { fill_smp(8); }
    
      var str = '';
      if ( (units<=0) || (units >3200) ) {
        alert('Sample size out of range'); 
      } else {
    // alternate display
    //    document.getElementById('batch_smp').value = smp.join(',');
        for (var i=0; i<smp.length; i++) {
          str += padLeft(smp[i],3)+',';
          if ((i&#37;10) == 9) { str += '\n'; }
        }
      }
      document.getElementById('batch_smp').value = str;
    }
    //]]>
    </script>
    </head>
    <body>
    <input type="text" id="batch_size" value='10'>Size<br>
    <button onclick="randon_sample()">Recalc</button><br>
    <textarea id="batch_smp" rows="20" cols="50"></textarea>
    </body>
    </html>
    It is not a problem to be a beginner at JS as everyone was at one time or another.
    Keep trying and learn from the mistakes while trying to avoid repeating them.
    Last edited by JMRKER; 11-29-2011 at 12:43 PM.

  12. #12
    Join Date
    Jan 2009
    Location
    Insanity
    Posts
    1,131
    Problem in real terms is you need to understand the rules and unfortunately you have no cheats in programming.

    My school tutor drilled it in to us that a program is just a collection of smaller problems that need solving and you need to tackle each element one at a time. I will often get an idea and just bash out the code I am looking to create and if I can not remember a function or method, I make one up but make it obvious that I have to research that method or way of accessing information.

    My tutor also said that you should always develop and evolve methods of doing things and be conversant in at least a couple of ways of doing the same job as each "Level" of coding has its place. It is also best to develop a code base of tools that you know works 100&#37; and use them to aid your code development.

    Avoid things like JQuery, Moo and whoever else wanders in off the street offering a way to simple site coding, well see the forums here ! Does it?

    Anyway, the important thing is to try, unlike other hobbies where you can experiment, the most you can do is break; your code.
    We all have baggage to carry in life, unfortunately for me I always get the trolley with the wonky wheel...
    Code:
    Youre = {
          STILL_not_getting_it:function(){
               alert("YOU, the original poster / thread starter NEED to POST the code and NOT a LINK.");
          },
          MissingThePoint:function(msg){
                alert("You're missing the point. " + msg);
          }
    }
    Youre.STILL_not_getting_it();

  13. #13
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,252
    It could be useful to know if the nbr numbers are always choose without repetitions between 1 and 500, or if the problem is only to sort randomly nbr numbers ! In the first case, this function which avoid to sort 500 numbers to choose only a small number of them (nbrVlu), could solve a part of the question.
    Code:
    var ttlVlu=500;
    function randList(nbrVlu){var nbrLst=0,lst='',firedVlu={}; 
    	do {var rnkVlu=1+Math.floor(Math.random()*(ttlVlu-nbrLst));
    		for (var i=1;;i++) if (typeof(firedVlu[i])!='number' && !(--rnkVlu)){
    			firedVlu[i]=1;lst+=','+i;break;}
    		nbrLst++} 
    	while (nbrLst!=nbrVlu);
    	lst=lst.substr(1).split(/,/g).sort(function(a,b){return a-b;}).join(', ');
    	return lst;
    }
    alert(randList(10))// give 10 random values (betwen 1 and 500) whitout repetitions

  14. #14
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,259

    Lightbulb

    Quote Originally Posted by 007Julien View Post
    It could be useful to know if the nbr numbers are always choose without repetitions between 1 and 500, or if the problem is only to sort randomly nbr numbers ! In the first case, this function which avoid to sort 500 numbers to choose only a small number of them (nbrVlu), could solve a part of the question.
    Code:
    ...
    The code I posted was a compromise between the two.
    It only creates the number of elements requested and randomizes those so that there are no repeats.

    Another way would be to create the maximum size of elements needed, randomize those
    and choose only the first 8 or 15 or whatever are needed per the requirements.

    To 'resa':
    Using the random()*unit calculation will NOT guarantee NO repeating numbers.

  15. #15
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,252
    I simply meant that it is totally useless to sort out randomly 500 values to choose randomly 8 or 15 ranks without repetitions.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles