html - Javascript random generation -
i'm trying make td , tr random number of columns , and rows when window refreshed. not sure doing wrong math here. haven't use function before know not right.
<!doctype html> <html onmousedown='event.preventdefault();'> <head> <title> boxes </title> <meta charset='utf-8'> <style> table { border-spacing: 6px; border: 1px rgb(#ccc); margin-top: .5in; margin-left: 1in; } td { width: 40px; height: 40px; border: 1px solid black; cursor: pointer; } </style> <script>
this function returns random value between min , max inclusive.
function r(min, max) { var range = math.abs(max-min)+1; return math.floor((math.random()*range) + min); } </script> </head> <body> <table> <tbody> <tr> <td> <td> <td> <td> <tr> <td> <td> <td> <td> <tr> <td> <td> <td> <td> <tr> <td> <td> <td> <td> <script>
use document.write() , for-loops make rows x cols table of empty cells styled according rules in style section. rows , cols should set random number between 4 , 16. each time page re-loaded table should different size.
for(r=4; r<16; r++){ var row ="td"; for(c=4; c<16;c++){ row+="tr"; }console.log(row); } </script> </tbody> </table> </body> </html>
here in example, have added script directly within body append required html keep simple
about code : well,in posted snippet using console.log() used writing output console not on web page in order have add document object (your page) simple method use
document.write('markup here');
follow this link know write method.
about how rows , cols generated ie. math.random() * (max - min) + min
here best explanation
table { border-spacing: 6px; border: 1px rgb(#ccc); } td { width: 20px; height: 40px; border: 1px solid black; cursor: pointer; }
<table border="1"> <script type="text/javascript"> //lets first set min , max here want min 4 , max 16 declare here. var min = 4, max =16; var row = math.random() * (max - min) + min; var cols = math.random() * (max - min) + min; //lets print someoutput for(var i=0;i<row;i++) { document.write("</tr>"); // printing html use tags <tr> not tr for(var j=0;j<cols;j++) { document.write("<td>dummy</td>"); // printing html use tags <td> not td } document.write("</tr>"); } </script> </table>
Comments
Post a Comment