Showing posts with label javascript validation. Show all posts
Showing posts with label javascript validation. Show all posts

Monday, February 29, 2016

Disable Back Button using Javascript




User tries to use back button for most of the applications and it is valid, but few of the cases is required to disable the back button and also restrict the user.

It would be very useful when the user is on payment page. Below is the code to disable the back button in Browser.

var currentURL = window.location.pathname + window.location.search;
 history.pushState(null, null, currentURL);
 window.addEventListener('popstate', function(event) {
  history.pushState(null, null, currentURL);
 });

It works in all major browsers

Tuesday, July 7, 2015

Trigger onchange event manually using Javascript


Below is the code to trigger onchange event for an element using javascript.

Usage of the method can be, when we want to call the onchange event on page loads or on by changing the text box value for other textbox.


if(document.fireEvent) {
    document.getElementById("myElement").fireEvent('onchange');
} else {
    var event = document.createEvent("HTMLEvents");
    event.initEvent("change",true,false);

    document.getElementById("myElement").dispatchEvent(event);
}

Whereas in jQuery, we can simply call the below method.

jQuery('myElement').change();

Thursday, July 24, 2014

Javascript: trim function support in all browsers



In Javascript, when we want to remove spaces in a string, we would be using trim function which is supported in all major browsers. See below code to use trim function in Javascript.

var str = "     message to trim    ";
document.write(str.trim());  // this code will prints as message to trim in the body.

But the above trim() function doesnot support in IE. To support the same functionality in IE too, add the below code to work as expected.

if (typeof String.prototype.trim !== "function") {
    String.prototype.trim = function () {
        return this.replace(/^\s+|\s+$/g, "")
    }
}


Sunday, December 1, 2013

Value of CKeditor using Javascript


To get the value of the CKeditor content using Javascript or jQuery. We need to use the below syntax.

CKEDITOR.instances['article_long_desc'].getData().length => It provides the length of the content in the editor

CKEDITOR.instances['article_long_desc'].getData() => It retrieves the value of the Textarea


Where "article_long_desc" is the textarea name


Sunday, October 6, 2013

Verify whether HTML object has the event using javascript or jQuery

We would be using multiple events or plugins to get our requirement done using jQuery.

While adding them we may not know whether the plugin is activated or not that gives error to the browser if it does not initiate and stops the next line of scripts in jQuery which we should not be doing. 

To get rid of this, we can use jQuery hasOwnProperty which tells whether the HTML object has the event which we are checking for.

Below is the sample code:

Consider we have included the CKEDITOR in the script and it applies for the textareas.


<html>
<head>
<script type="text/javascript" src="ckeditor.js">
<title>Test Object Event Existence</title>
</head>
<body>
<ul>
     <li>First name: <input type="text" name="fname" /> </li>
     <li>Last name: <input type="text" name="lname" /> </li>
     <li>Address: <textarea name="address" id="address" ></textarea></li>
</ul>
</body>
</html>
For the above script, to check whether the textareas has CKEDITOR or not we can check as below

$('#address').hasOwnProperty('CKEDITOR') 

If it exists it returns true else returns false.


Monday, July 29, 2013

Decode html entities using javascript

Below is the code to decode the html entities using javascript rather than the Server side scripting

function decodeEntities(input) {
    var y = document.createElement('textarea');
    y.innerHTML = input;
    return y.value;
}

Above function just receives the html values like below

var str = "<p>Hello World<br />This is the test message";

When we pass the above HTML string to the function it returns as below,

calling the JAVASCRIPT function 

decodeEntities(str)

Output is: "&lt;p&gt;Hello World&lt;br/&gt;This is the test message";

Thursday, July 18, 2013

Disable right click in a page using javascript


When we want to restrict the right click of the mouse in some of the pages, need to add the below code in the <head> </head> tag within the JAVASCRIPT.

<script type="text/javascript">
var message="Sorry, Right Click has been disabled";
        function clickIE() {if (document.all) {window.console.log(message);return false;}}
       
       function clickNS(e) {
if (document.layers||(document.getElementById&&!document.all)) {
       if (e.which==2||e.which==3) {window.console.log(message);return false;}
}
}
        if (document.layers)
        {document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
        else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
        document.oncontextmenu=new Function("return false")

</script>


Thursday, January 3, 2013

javascript validation for file upload

Below is the article for adding javascript validation (or) jquery validation for a file upload that makes our life easier whether the file upload is a valid type or not.


if($('#upload_file').val() != '')
{
        var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"]; // Can change the extensions if we need for doc type or something else
        if($('#upload_file').val() != '')
        {
            var sFileName = $('#upload_file').val();
            var blnValid = false;
            for (var j = 0; j < _validFileExtensions.length; j++)
            {
                var sCurExtension = _validFileExtensions[j];
                if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                    blnValid = true;
                    break;
                }
            }
            if(!blnValid)
            {
               alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                $('#upload_file').focus();
                return false;
            }
        }
 }