Friday, August 1, 2014

Jquery to generate Random Number




Please visit my new Web Site https://coderstechzone.com



In many forums i found a question "How to generate a Random Number using Jquery?". Its easy to generate a Random number because Jquery provides us builtin Math library function Math.random() to generate the number. To get the output you have to put a number range. Then the the mehod Math.random() will give you a Random Number. You can also use this technique for dice, random image script, or random link generator.

I have tried to produce the below output:

Jquery Random Number

To do that add an asp.net aspx page and write the below code under form tag:
<asp:Button ID="Button1" runat="server" Text="Generate Random Number" />
    <div id="divNumber">
        
    </div>

Now under head tag write the below JQuery function or method:
<script type="text/javascript">
        $(document).ready(function() {
            $("#Button1").click(function() {
                var Random_Number = Math.ceil(Math.random()*500); // Generate random number between 1 and 500               
                $("#divNumber").append("<b>The Number is: </b>"+Random_Number+"</br>");
                return false;
            });
        });
    </script>
The complete markup code should be:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Jquery_RandomNumber.aspx.cs" Inherits="Jquery_RandomNumber" %>

<!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 runat="server">
    <title>Jquery to generate Random Number</title>
    <script src="Script/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#Button1").click(function() {
                var Random_Number = Math.ceil(Math.random()*500); // Generate random number between 1 and 500               
                $("#divNumber").append("<b>The Number is: </b>"+Random_Number+"</br>");
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="Button1" runat="server" Text="Generate Random Number" />
    <div id="divNumber">
        
    </div>

    </div>
    </form>
</body>
</html>
Now run the example and hope you can generate random number using JQuery.

0 comments:

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash