Question

I need the numbers and letters to be somewhat like this 0000-00-0000A. I am working on a project so when i place a coupon the random numbers and letter will appear on the coupon id where i place it at, but for every coupon the numbers and letter is different. And yes i am new to coding 2 months in and i think i am doing alright except for this random number thing. The examples of what i am doing is below.

<!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>
<style>
#coupon{
     width: 600px;
     height:auto;
     top:145px;
    background: #FFFF95;
    margin: 2px auto;
    border: 1px solid #000000;
    text-align: center;
    -webkit-border-top-left-radius:06px;
    -webkit-border-top-right-radius:06px;
    -webkit-border-bottom-left-radius:06px;
    -webkit-border-bottom-right-radius:06px;
    -moz-border-radius-topleft:06px;
    -moz-border-radius-bottomleft:06px;
    -moz-border-radius-topright:06px;
    -moz-border-radius-bottomright:06px;
    border-top-left-radius:06px;
    border-top-right-radius:06px;
    border-bottom-left-radius:06px;
    border-bottom-right-radius:06px;
    /* additional features, can be omitted */
    border:2px outset #093;
    padding:15px;
    font-size:15px;
    -moz-box-shadow: 0 0 15px #999;
    -webkit-box-shadow: 0 0 15px #999;
    box-shadow: 0 0 15px #999;
}


</style>
</head>

<body>
<div id="coupon" class="coupon">
<p>This can be the coupn area where the cupon is place and the deal can be read then printed!</p>
<div class="print-page" id="print-page">
  <p><a href=" #" onClick=" window.print()" >Print Deal</a></p>
</div>
<div class="coupon-id-number" id="coupon-id-number">0000-00-0000-A</div></div>

</body>
</html>

Please can anyone help me out?

Was it helpful?

Solution

If you would like to do this by JavaScript, you might need a function like

<script>
function genRandom() {
  var genNumber = function (length) {
        return ~~(Math.random() * length);
      },
      genChar = function () {
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXZ',
            index = genNumber(24);

        return chars.slice(index, index + 1);
      },
      arr = [genNumber(10000), genNumber(100), genNumber(10000), genChar()];
  return arr.join('-');
}

document.getElementById('coupon-id-number').innerHTML = genRandom();
</script>

OTHER TIPS

In java you would do something like:

Random random = new Random();
String couponCode = String.format("%04d-%02d-%04d-%s", random.nextInt(10000), random.nextInt(100), random.nextInt(10000), (char)(random.nextInt(26)+65));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top