Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

How to check if JavaScript is enabled

Suggested Videos
Part 70 - Set and get multiple cookies in JavaScript
Part 71 - Update and delete cookies
Part 72 - How to check if cookies are enabled



In this video we will discuss how to check if JavaScript is enabled or disabled. Let us understand this with an example.



We have a page that captures Name and Gender. Both fields are required. The page relies on JavaScript being enabled for performing validation. We should always have server side validation irrespective of whether we have client side validation or not. It is not a good practice to rely just on client side validation, but for the purpose of this demo, let us say we only have client side validation.

How to check if JavaScript is enabled

If JavaScript is enabled then we want to display the Name and Gender elements and the user can continue to use the application.

If JavaScript is disabled then we want to hide the Name and Gender elements and we want to display the following message.
It seems that you have disabled JavaScript. Please enable JavaScript.

The easiest way to detect if JavaScript is enabled is by using noscript tag. The content inside the <noscript> element will be displayed only if scripts are not supported, or are disabled in the user's browser. 

<noscript>
    <style type="text/css">
        .rootDiv
        {
            display: none;
        }
    </style>
    <h1>It seems that you have disabled JavaScript. Please enable JavaScript.</h1>
</noscript>
<div id="rootElement" class="rootDiv">
    <table border="1">
        <tr>
            <td>Name</td>
            <td>
                <input id="txtName" type="text" onfocus="validateIfEmpty('txtName')"
           onblur="validateIfEmpty('txtName')" onkeyup="validateIfEmpty('txtName')"/>
            </td>
        </tr>
        <tr>
            <td>Gender</td>
            <td>
                <input id="txtGender" type="text" onfocus="validateIfEmpty('txtGender')"
           onblur="validateIfEmpty('txtGender')" onkeyup="validateIfEmpty('txtGender')"/>
            </td>
        </tr>
    </table>
</div>
<script type="text/javascript">
    function validateIfEmpty(control)
    {
        var controlToValidate = document.getElementById(control);
        if (controlToValidate.value == "")
        {
            controlToValidate.style.background = "red";
        }
        else
        {
            controlToValidate.style.background = "white";
        }
    }
</script>

JavaScript tutorial

1 comment:

  1. Hi Venkat,

    Thanks for your videos. Please give some videos on Angular JS and JQuery.

    Thank You

    ReplyDelete

It would be great if you can help share these free resources