Link to home
Start Free TrialLog in
Avatar of andreni78
andreni78

asked on

Javascript code to generate a random number

Requirements:
1. Scripts must work with NS4+, IE4+ and AOL most popular versions
2. When click a button name "Code Gen", it will generate a random code base on the below formular, then populate the text box with the new code, re-click "Code Gen" button will regenerate and replace the text box with the new random code.

The text box name is: name="rqaRedemptionCode"

3. Formular:

[Year Code + Month Code + Date] - [random 4 digit number]

Year Code = A to J (A=0 to J=9, if year end with 0 then A, current year is: 5 or F)
Month Code = B to M (B=1 to M=12, current month is May, then F)
Date = actual date (1 to 31)

random 4 digit number=any popular method of produce 4 digit random number

For example: today date is 2005, 5,15
example code is: FF15-5624

4. Please provide a ready to use code with html for testing.

Thanks, Maximum 500 as always.
ASKER CERTIFIED SOLUTION
Avatar of Batalf
Batalf
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I forgot the name of the form field.

You can change the name in the function from

document.myForm.codeField.value = code;    

to

document.myForm.rqaRedemptionCode.value = code;    

and the text field in the form from

<input type="text" name="codeField">

to

<input type="text" name="rqaRedemptionCode">

Batalf

Avatar of william007
william007

Hi!~ Batalf
just curious, I have seen you put d.getMonth()/1 not only one time...
I have tested d.getMonth() is a Number type(I only test in IE6 and firefox), what is the significant to divide by one?
Hi william007,

It's because Javascript uses '+' both to concatinate strings and to add numbers, and because it doesn't fully support primitive variable types.

So I perform an arithmetic operation on the numbers to get the values added instead of concatinated. After checking, it doesn't look like it's needed in this example, but I have found it to be a good habit to always do it this way.

Example that illustrates it:

      <script type="text/javascript">
      var variable1 = '100';
      alert(variable1 + 5); // Alerts 1005
      alert(variable1/1 + 5); // Alerts 105
      </script>
Batalf





Oic, is for "security purpose":-)
Avatar of andreni78

ASKER

Hi Batalf,

Thank you for the superfast response. It works perfectly.

Glad I could help!

Batalf