Menu ▼


<< < 1 2 3 > >>

Below JavaScript function getdatetime() will return the date string in mm/dd/yyyy hhmmss ampm format. You need to pass date as parameter that need to be returned in the format mm/dd/yyyy hhmmss ampm. If you want current date in the format then you can simple call the function as getdatetime(new Date());

Example

JavaScript Function

function getdatetime(dt) {
    var res = "";
    res += formatdigits(dt.getMonth() + 1);
    res += "/";
    res += formatdigits(dt.getDate());
    res += "/";
    res += formatdigits(dt.getFullYear());
    res += " ";
    res += formatdigits(dt.getHours() > 12 ? dt.getHours() - 12 : dt.getHours());
    res += ":";
    res += formatdigits(dt.getMinutes());
    res += ":";
    res += formatdigits(dt.getSeconds());
    res += " " + dt.getHours() > 11 ? " PM" : " AM";
    return res;
}
function formatdigits(val) {
    val = val.toString();
    return val.length == 1 ? "0" + val : val;
}

Calling function:

var dtformated = getdatetime(new Date());
$("#divdatetime").html(dtformated);

Source code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
        function getdatetime(dt) {
            var res = "";
            res += formatdigits(dt.getMonth() + 1);
            res += "/";
            res += formatdigits(dt.getDate());
            res += "/";
            res += formatdigits(dt.getFullYear());
            res += " ";
            res += formatdigits(dt.getHours() > 12 ? dt.getHours() - 12 : dt.getHours());
            res += ":";
            res += formatdigits(dt.getMinutes());
            res += ":";
            res += formatdigits(dt.getSeconds());
            res += " " + dt.getHours() > 11 ? " PM" : " AM";
            return res;
        }
        function formatdigits(val) {
            val = val.toString();
            return val.length == 1 ? "0" + val : val;
        }
        $(document).ready(function () {
            var dtformated = getdatetime(new Date());
            $("#divdatetime").html(dtformated);
        });
    </script>
</head>
<body>
    <div id="divdatetime">
    </div>
</body>
</html>

Read More...
Submited By : mrkraju On 25 Nov 2016

Below JavaScript function getdate() will return the date string in mm/dd/yyyy format. You need to pass date as parameter that need to be returned in the format mm/dd/yyyy. If you want current date in the format then you can simple call the function as getdate(new Date());

Example:

Javascript Function:

function getdate(dt) {
    var res = "";
    if ((dt.getMonth() + 1).toString().length < 2)
        res += "0" + (dt.getMonth() + 1).toString();
    else
        res += (dt.getMonth() + 1).toString();
    res += "/";
    if (dt.getDate().toString().length < 2)
        res += "0" + dt.getDate().toString();
    else
        res += dt.getDate().toString();
    res += "/" + dt.getFullYear().toString();
    return res;
}

Calling function:

var dtformated = getdate(new Date());
$("#divdatetime").html(dtformated);

Source code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
        function getdate(dt) {
            var res = "";
            if ((dt.getMonth() + 1).toString().length < 2)
                res += "0" + (dt.getMonth() + 1).toString();
            else
                res += (dt.getMonth() + 1).toString();
            res += "/";
            if (dt.getDate().toString().length < 2)
                res += "0" + dt.getDate().toString();
            else
                res += dt.getDate().toString();
            res += "/" + dt.getFullYear().toString();
            return res;
        }
        $(document).ready(function () {
            var dtformated = getdate(new Date());
            $("#divdatetime").html(dtformated);
        });
    </script>
</head>
<body>
    <div id="divdatetime">
    </div>
</body>
</html>

Read More...
Submited By : mrkraju On 17 Nov 2016

JavaScript replace() method will replace only the first occurrence of the string. If you want to replace all the occurrences of a string then you have to write your custom code. By using JavaScript regular expressions or by JavaScript array split and join we can replace the all occurrences of spaces, characters, commas or the given input. Lets see how to do that with below examples.

Replace all spaces in a string

var input:'Hello h o w Ar e you?'
input = input.replace(/ /g,'');

Output
//'HellohowAreyou?'


Replace all commas in a string

var input:'Hello, Welcome, to, dotnet,learners,.com'
input = input.replace(/,/g,'');

Output
//'Hello Welcome to dotnetlearners.com'


Replace all occurrences of specific word in a string
Below example will replace all occurrences of the word 'and'

var input:'Example and to and replace and all and the and occurrences and of and a and specific and word'
input = input.replace(/and/g,'');

Output
//'Example to replace all the occurrences of a specific word'


JavaScript function to replace all occurrences of a string


function replaceAll(input, replace, replacewith) {
    return input.replace(new RegExp(replace, 'g'), replacewith);
}

Usage
var input:'Example and to and replace and all and the and occurrences and of and a and specific and word'
replaceAll(input, 'and', '');


Replace all occurrences using JavaScript array split and join.


function replaceAll(input, replace, replacewith) {
    return input.split(replace).join(replacewith);
}

Usage
var input:'Example and to and replace and all and the and occurrences and of and a and specific and word'
replaceAll(input, 'and', '');


Note
Even in JQuery there is no replaceAll function to replace all the occurrences of a string. So you have to use any one of the above JavaScript approach.

Read More...
Submited By : mrkraju On 04 Dec 2015

The below JavaScript function will validate date for the following formats.
1. mm/dd/yyyy
2. mm/dd/yy
3. mm-dd-yyyy
4. mm-dd-yy

JavaScript function

//Checks date for mm/dd/yyyy, mm/dd/yy, mm-dd-yyyy and mm-dd-yy format.
function checkDate(inputdate) {
    if (inputdate == '')
        return false;

    var rxDatePattern = /^(0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-]((?:19|20)\d\d)$/

    var dtArray = inputdate.match(rxDatePattern);
    if (dtArray == null) {
        rxDatePattern = /^(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/]((?:19|20)\d\d)$/
        dtArray = inputdate.match(rxDatePattern);
        if (dtArray == null)
            return false;
    }

    dtMonth = dtArray[1];
    dtDay = dtArray[2];
    dtYear = dtArray[3];

    if (dtMonth < 1 || dtMonth > 12)
        return false;
    else if (dtDay < 1 || dtDay > 31)
        return false;
    else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31)
        return false;
    else if (dtMonth == 2) {
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
        if (dtDay > 29 || (dtDay == 29 && !isleap))
            return false;
    }
    return true;
}

Example
date validation in javascript

Example source code

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script language="javascript">
        //Checks date for mm/dd/yyyy, mm/dd/yy, mm-dd-yyyy and mm-dd-yy format.
        function checkDate(inputdate) {
            if (inputdate == '')
                return false;

            var rxDatePattern = /^(0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-]((?:19|20)\d\d)$/

            var dtArray = inputdate.match(rxDatePattern);
            if (dtArray == null) {
                rxDatePattern = /^(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/]((?:19|20)\d\d)$/
                dtArray = inputdate.match(rxDatePattern);
                if (dtArray == null)
                    return false;
            }

            dtMonth = dtArray[1];
            dtDay = dtArray[2];
            dtYear = dtArray[3];

            if (dtMonth < 1 || dtMonth > 12)
                return false;
            else if (dtDay < 1 || dtDay > 31)
                return false;
            else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31)
                return false;
            else if (dtMonth == 2) {
                var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
                if (dtDay > 29 || (dtDay == 29 && !isleap))
                    return false;
            }
            return true;
        }

        function validatedate() {
            if (checkDate(document.getElementById("txtDate").value)) {
                document.getElementById("divmsg").innerHTML = "Valid Date.";
                document.getElementById("divmsg").style.color = "green";
            }
            else {
                document.getElementById("divmsg").innerHTML = "Invalid Date.";
                document.getElementById("divmsg").style.color = "red";
            }
        }

    </script>
</head>
<body>
    Date :
    <input id="txtDate" type="text" value="11/19/2015">
    <input type="button" value="Validate" onclick="validatedate();" />
    <br />
    <br />
    <div id="divmsg">
    </div>
</body>
</html>

Read More...
Submited By : mrkraju On 19 Nov 2015

JavaScript inbuilt array reverse() method reverses the order of the elements in an array (original array will be reversed).

Example
Original Array: var ary = ["One", "Two", "Three", "Four", "Five"];



Output


Syntax
document.getElementById("snpresult").innerText = ary.reverse();

Source code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
<script language="javascript">
    var ary = ["One", "Two", "Three", "Four", "Five"];
    function reverseArray() {
        document.getElementById("snpresult").innerText = ary.reverse();
    }
</script>
</head>
<body>
Original Array:
var ary = ["One", "Two", "Three", "Four", "Five"];
<br />
<br />
<input type="button" onclick="reverseArray();" value="Print Reverse Array" />
<br />
<br />
<span id="snpresult"></span>
</body>
</html>
Read More...
Submited By : mrkraju On 09 Nov 2015
Read More...
Submited By : John Prathip On 16 Jun 2015

This example will shows you how to replace single quote form a string. Default javascript replace method will replace the first occurrence of the single quote, to replace all the occurrences we have to use regular expression.

  • Removing all the single quotes from a string.
    var outputstr= inputstring.replace(/'/g,'');

  • Replacing all the single quotes with double quote in a string.
    var outputstr= inputstring.replace(/'/g,'"');


Example:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script language="javascript">
        function RemoveSingleQuotes() {
            var outputstr = $("#txtinput").val().replace(/'/g, '');
            alert(outputstr);
        }
        function ReplaceSingleQuotes() {
            var outputstr = $("#txtinput").val().replace(/'/g, '"');
            alert(outputstr);
        }    
    </script>
</head>
<body>
    <div>
        <input type="text" id="txtinput" />&nbsp;&nbsp;
        <input type="button" value="Remove Single Quotes" onclick="RemoveSingleQuotes();" />&nbsp;&nbsp;
        <input type="button" value="Replace Single Quotes" onclick="ReplaceSingleQuotes();" />
    </div>
</body>
</html>
Read More...
Submited By : mrkraju On 30 Apr 2015

In this example we will see how to redirect one web page to another web page using javascript. we need to set the redirect url to window.location.href, then the web page will be redirect to given url.

Syntax: window.location.href = "url here";

Example

Redirect this web site to

  • If we give the relative path as url, then the page will be redirected to another page with in the web site.
    • ex : if we give the url as "/blogs/" then the page will be redirect to "http://www.dotnetlearners.com/blogs/"
  • we can give the another website url, so that it will redirect to another web site.
    • ex: http://www.google.com

Source Code

<html>
<head>
    <title></title>
    <script language="javascript">
        function redirectwebsite() {
            var url = document.getElementById("txtwebsiteurl").value;
            window.location.href = url;
        }
    </script>
</head>
<body>
    Redirect this web site to
    <input type="text" id="txtwebsiteurl" value="http://www.dotnetlearners.com" style="width: 410px;" />
    <input type="button" value="Redirect" onclick="redirectwebsite();" />
</body>
</html>
Read More...
Submited By : mrkraju On 22 Sep 2014

Some times we may need to perform same action multiple times. by using javascript "setInterval" function we can call specific functionality continuously in a specific time interval. to stop the loop we need to use the "clearInterval" function.

Syntax : var objInterval = setInterval(code, delay);
where code is the set of action or a function, and delay is the time interval in milliseconds.
               clearInterval(objInterval);
where objInterval is the interval id.

Example

Count down from

JavaScript

var countdown = 0;
var objInterval;
function startcountdown() {
    countdown = parseInt(document.getElementById("txtcountdown").value, 10);
    objInterval = setInterval(showcountdown, 1000);
}
function showcountdown() {
    document.getElementById("spncountdown").innerHTML = countdown;
    if (countdown < 0) {
        clearInterval(objInterval);
        document.getElementById("spncountdown").innerHTML = "Completed.... setInterval cleared.";
    }
    else
        countdown--;
}

Source Code

<html>
<head>
    <title></title>
    <script language="javascript">
        var countdown = 0;
        var objInterval;
        function startcountdown() {
            countdown = parseInt(document.getElementById("txtcountdown").value, 10);
            objInterval = setInterval(showcountdown, 1000);
        }
        function showcountdown() {
            document.getElementById("spncountdown").innerHTML = countdown;
            if (countdown < 0) {
                clearInterval(objInterval);
                document.getElementById("spncountdown").innerHTML = "Completed.... setInterval cleared.";
            }
            else
                countdown--;
        }
    </script>
</head>
<body>
    Count down from
    <input type="text" id="txtcountdown" value="10" style="width: 40px; text-align: center;" />
    <input type="button" value="Start" onclick="startcountdown();" /><sapn id="spncountdown"
        style="color: Blue; font-size: 20px; padding-left: 20px;"></sapn>
</body>
</html>
Read More...
Submited By : mrkraju On 22 Sep 2014

When we want to perform a particular action or call a particular javascript method after a specific time, then we can achieve it by using javascript inbuilt function setTimeout.

"setTimeout" function will take 2 parameter , the first one is function and the second parameter is time in milliseconds.

Syntax : setTimeout(function, timeout);
where the function can be write there it self, are can write separately and can pass the function name as parameter.

Example

alert me after seconds

Method 1 : Writing javasript method as a parmeter

function showalert() {
    var timedelay = parseInt(document.getElementById("txttimerdelay").value, 10) * 1000;
    setTimeout(function () { alert(new Date()); }, timedelay);
}

Method 2 : Writing javasript method separately and passing method name as a parmeter

function showalert() {
    var timedelay = parseInt(document.getElementById("txttimerdelay").value, 10) * 1000;
    setTimeout(showtime, timedelay);
}
function showtime() {
    alert(new Date());
}

Source Code

<html>
<head>
    <title></title>
    <script language="javascript">
        function showalert() {
            var timedelay = parseInt(document.getElementById("txttimerdelay").value, 10) * 1000;
            setTimeout(function () { alert(new Date()); }, timedelay);
        }
        function showtime() {
            alert(new Date());
        }
    </script>
</head>
<body>
    alert me after
    <input type="text" id="txttimerdelay" value="2" style="width: 40px; text-align: center;" />
    seconds<input type="button" value="Show Alert" onclick="showalert();" />
</body>
</html>
Read More...
Submited By : mrkraju On 21 Sep 2014
<< < 1 2 3 > >>




Search dotnetlearners.com