Do a postback from javascript with ASP .NET AJAX

If you want to do a postback from javascript with ASP .NET AJAX and the aspx page contains a

<form id="mainForm" runat="server">

, you can create and use the javascript function to do a postback from javascript:



function
DoPostBack() {

    var form = document.getElementById(‘mainForm’);

    form.submit();

}

Prevent Internet Explorer, Google Chrome and Firefox from entering address bar after pressing TAB or SHIFT-TAB on the last or first element of the page

The normal behavior of a browser is to select the address bar after pressing tab on the last element of the page or shift tab on the first element on the page. Some customer who want to port a Windows application to a Web application want to copy the exact functionality of the Windows application (this is of course not a good idea) and want the tab order to stay in the web form. The following ASP .NET page shows how to make this functionality work on a web form, using CSS and JavaScript. 

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Rvl.HelperTools.Website._Default" %>

<!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>Test Page</title>

    <style type="text/css">
        .FirstElementOnPage
        {
            position: absolute;
            top: -120px;
            border: solid 1px white;
            height: 1px;
            width: 1px;
        }
        .LastElementOnPage
        {
            position: absolute;
            top: -100px;
            border: solid 1px white;
            height: 1px;
            width: 1px;
        }
        .LastColumn
        {
            border-left: solid 10px white;
            text-align: left;
            width: 100%;
        }
    </style>

    <script language="javascript" type="text/javascript">
        var m_shiftKeyPressed = false;

        // This function focusses the given element. The funcion has a parameter event,
        // because the global event object is only defined in Internet Explorer.
        function SetFocusToElement(event, elementId, shiftKeyValue) {

            // Determine if Shift key is pressed.
            if (event.shiftKey) {
                // IE defines a global object event with a property shiftKey, use this property
                shiftKeyIsPressed = event.shiftKey;
            }
            else {
                // Google chrome and firefox don't define a global event object and the event onblur event parameter does not contain a property shiftKey.
                // Use the determined value for m_shiftKeyPressed in the onKeyPressedDown event handler
                shiftKeyIsPressed = m_shiftKeyPressed;
            }

            // Only focus when parameter shiftKeyValue == shiftKeyIsPressed
            if (shiftKeyIsPressed == shiftKeyValue) {

                // Find the element in DOM
                var elementToFocus = document.getElementById(elementId);

                // Must use setTimeout for google chrome, to set focus.
                var statementsToExcecute = 'document.getElementById(\'' + elementId + '\').focus()';
                setTimeout(statementsToExcecute, 1);
            }

            // Must return true, for firefox to work
            return true;
        }
        function OnKeyUpFocusChange(event) {
            // Save if shift key is pressed, for use in onblur eventhandler.
            m_shiftKeyPressed = event.shiftKey;
            return true;
        }
    </script>

</head>
<body>
    <form id="mainForm" runat="server">
        <input id="firstElementOnPage" type="text" class="FirstElementOnPage" />
        <table>
            <tr>
                <td><asp:Label ID="customerLabel" runat="server" Text="Customer"></asp:Label></td>
                <td class="LastColumn"><asp:TextBox ID="customerTextBox" runat="server" Text="Microsoft" onkeydown="OnKeyUpFocusChange(event);"
                onblur="SetFocusToElement(event, 'submitButton', true);"></asp:TextBox></td>
            </tr>
            <tr>
                <td><asp:Label ID="cityLabel" runat="server" Text="City"></asp:Label></td>
                <td class="LastColumn"><asp:TextBox ID="cityTextBox" runat="server" Text="Redmond"></asp:TextBox></td>
            </tr>
            <tr>
                <td><asp:Label ID="supplierLabel" runat="server" Text="Supplier"></asp:Label></td>
                <td class="LastColumn"><asp:TextBox ID="supplierTextBox" runat="server" Text="IBM"></asp:TextBox></td>
            </tr>
            <tr>
                <td><asp:Label ID="productsLabel" runat="server" Text="Products"></asp:Label></td>
                <td class="LastColumn"><asp:TextBox ID="productsTextBox" runat="server" Text="Windows"></asp:TextBox></td>
            </tr>
        </table>
        <input id="submitButton" type="button" value="Submit" onblur="SetFocusToElement(event, 'customerTextBox', false);" />
        <input id="lastElementOnPage" type="text" class="LastElementOnPage"  />
    </form>
</body>
</html>

image

After pressing the tab key on when the Submit button has focus, the customer textbox will be focused.

Change div or table width and height, with CSS rules based on user screen resolution in ASP .NET by using javascript

If you want to change the width of your main div or main table element in ASP .NET, you can use margin-left: auto; and margin-right: auto; to dynamically change the width of these elements based on the browser width, but this width will vary when you change you’re browser screen and older browser (IE6) don’t support the min-width css statement. If you want to have an exact width of the main element you can set the width by using css, but then you will have to choose a fixed value for all user screen resolutions. With the use of javascript, you can change the css value dynamically based on the user screen resolution.

If the main table or main div has an exact width, you can base all other layout inside relative to this width, by using margin’s and padding’s.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Rvl.HelperTools.Website._Default" %>

<!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>Untitled Page</title>

    <!-- Load css styles -->
    <style type="text/css">
        .Main
        {
            background-color:Silver;
            margin-left: auto; /* Center mainTable for >= IE6  */
            margin-right: auto; /* Center mainTable for >= IE6  */
            width: 800px;
        }
    </style>

    <!-- Correct css styles based on user screen resolution -->
    <script language="javascript" type="text/javascript">

        // Find the first css class based on parameter [className].
        function GetStyleClass(className) {

            // Loop all loaded css style sheets
            for (var s = 0; s < document.styleSheets.length; s++) {

                // Check if browser uses [rules]
                var rules;
                if (document.styleSheets[s].rules) {
                    rules = document.styleSheets[s].rules;
                }

                // Check if browser uses [cssRules]
                if (document.styleSheets[s].cssRules) {
                    rules = document.styleSheets[s].cssRules;
                }

                // Check if browser supports css rules
                if (rules) {
                    // Loop rules in css stylesheet
                    for (var r = 0; r < rules.length; r++) {

                        // Stop search and return rule, when classname is found
                        if (rules[r].selectorText == '.' + className) {
                            return rules[r];
                        }
                    }
                }
            }

            // If css class not found, return null.
            return null;
        }
        // Convert a css px value to int.
        function ConvertCssPxToInt(cssPxValueText) {

            // Set valid characters for numeric number.
            var validChars = "0123456789.";

            // If conversion fails return 0.
            var convertedValue = 0;

            // Loop all characters of
            for (i = 0; i < cssPxValueText.length; i++) {

                // Stop search for valid numeric characters,  when a none numeric number is found.
                if (validChars.indexOf(cssPxValueText.charAt(i)) == -1) {

                    // Start conversion if at least one character is valid.
                    if (i > 0) {
                        // Convert validnumbers to int and return result.
                        convertedValue = parseInt(cssPxValueText.substring(0, i));
                        return convertedValue;
                    }
                }
            }

            return convertedValue;
        }

        // Get main table css class
        var mainClass = GetStyleClass('Main');

        // Change main table width based on user screen resolution.
        if (mainClass) {

            // Use default css width, if screen width is less then default css width.
            var width = ConvertCssPxToInt(mainClass.style.width);

            // Use screen width - 50px if screen width is greather the default css width.
            if (screen.width > width) {
                width = screen.width - 45;
            }

            // Change the width of the main table
            mainClass.style.width = width + 'px';
        }
    </script>
</head>
<body>

    <form id="form1" runat="server">
    <div class="Main">
        <p>Some text</p>
        <p>Some more text...</p>
    </div>
    </form>
</body>
</html>

Alter CSS class with javascript for usage in ASP .NET

To alter a CSS class with javascript, you can use the following function:

        // Find the first css class based on parameter [className].
        function GetStyleClass(className) {

            // Loop all loaded css style sheets
            for (var s = 0; s < document.styleSheets.length; s++) {

                // Check if browser uses [rules]
                var rules;
                if (document.styleSheets[s].rules) {
                    rules = document.styleSheets[s].rules;
                }

                // Check if browser uses [cssRules]
                if (document.styleSheets[s].cssRules) {
                    rules = document.styleSheets[s].cssRules;
                }

                // Check if browser supports css rules
                if (rules)
                {
                    // Loop rules in css stylesheet
                    for (var r = 0; r < rules.length; r++) {

                        // Stop search and return rule, when classname is found
                        if (rules[r].selectorText == '.' + className) {
                            return rules[r];
                        }
                    }
                }
            }

            // If css class not found, return null.
            return null;
        }

Usage of the function in ASP .NET:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Rvl.HelperTools.Website._Default" %>

<!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>Untitled Page</title>

        <!-- Load css styles -->
    <style type="text/css">
        .Main
        {
            background-color:Silver;
            margin-left: auto; /* Center mainTable for >= IE6  */
            margin-right: auto; /* Center mainTable for >= IE6  */
            width: 800px;
        }
    </style>

    <!-- Correct css styles based on user screen resolution -->
    <script language="javascript" type="text/javascript">

        // Find the first css class based on parameter [className].
        function GetStyleClass(className) {

            // Loop all loaded css style sheets
            for (var s = 0; s < document.styleSheets.length; s++) {

                // Check if browser uses [rules]
                var rules;
                if (document.styleSheets[s].rules) {
                    rules = document.styleSheets[s].rules;
                }

                // Check if browser uses [cssRules]
                if (document.styleSheets[s].cssRules) {
                    rules = document.styleSheets[s].cssRules;
                }

                // Check if browser supports css rules
                if (rules) {
                    // Loop rules in css stylesheet
                    for (var r = 0; r < rules.length; r++) {

                        // Stop search and return rule, when classname is found
                        if (rules[r].selectorText == '.' + className) {
                            return rules[r];
                        }
                    }
                }
            }

            // If css class not found, return null.
            return null;
        }

        // Get main table css class
        var mainClass = GetStyleClass('Main');

        // Change main table background color if class was found
        if (mainClass) {
            mainClass.style.backgroundColor = 'Red';
        }
    </script>
</head>
<body>

    <form id="form1" runat="server">
    <div class="Main">
        <p>Some text</p>
        <p>Some more text...</p>
    </div>
    </form>
</body>
</html>

How to convert a CSS px width or height value to int with javascript

If you want to alter an elements CSS width or height, you must first convert this value to an integer, because the CSS value can have units like px, cm etc.
To convert this value to an integer in javascript, use:

        // Convert a css px value to int.
        function ConvertCssPxToInt(cssPxValueText) {

            // Set valid characters for numeric number.
            var validChars = "0123456789.";

            // If conversion fails return 0.
            var convertedValue = 0;

            // Loop all characters of
            for (i = 0; i < cssPxValueText.length; i++) {

                // Stop search for valid numeric characters,  when a none numeric number is found.
                if (validChars.indexOf(cssPxValueText.charAt(i)) == -1) {

                    // Start conversion if at least one character is valid.
                    if (i > 0) {
                        // Convert validnumbers to int and return result.
                        convertedValue = parseInt(cssPxValueText.substring(0, i));
                        return convertedValue;
                    }
                }
            }

            return convertedValue;
        }

Difference between return true; and return false; in javascript

see: http://bytes.com/groups/javascript/89023-difference-between-return-true-return-false

When you return something from a function, that value gets returned to the
caller. For instance, say I had a method to multiply two numbers. Maybe the
code looks like this:

function multiply(num1, num2) {
return num1 * num2;
}
result = multiply(2, 4);

The function multiply will return the result of it’s multiplication to
wherever it was called. The right-hand side of the result assignment is
where the function is called, so that is where the result is returned to.
So, in this case (with the parameters 2 and 4), it is the same as writing
result = 8;

When you are using return true or false with markup, you are indicating
whether or not you want the default action to happen after the javascript
has been executed. An example is needed:

<a href="somepage.html" onClick="alert(‘Hi’); return true;">Click Me</a>

When the link is clicked the javascript code for the onClick will run first,
and we get an alert. We have used return true, so that is saying when we
click OK to remove the alert, we do want to run the markup. So in this case
once we click OK to dismiss the alert, we would then be taken to
somepage.html. If we changed that to return false we would get the alert,
but wouldn’t go to somepage.html.

undefined vs null in javascript

There is a difference between a varaible declarde as:

var test;

and a variable declared as:

var test = null;

The first variable has a value of undefined whereas the second variable has a value of null;
Code example:

<script type="text/javascript">
        var test;
        if(test == null)
        {
            alert("The variable [test] equals [undefined] or [null]");
        }
        var test1 = null;
        if(test1 == null)
        {
            alert("The variable [test1] equals [undefined] or [null]");
        }
        var test2 = null;
        if(test2 === null)
        {
            alert("The variable [test2] equals [null] and not [undefined], because we use the operator [===] and not [==]");
        }
        var test3;
        if(test3 === undefined)
        {
            alert("The variable [test3] equals [undefined] and not [null], because we use the operator [===] and not [==]");
        }
    </script>

Set text on control with javascript

To set the text on a control with javascript use:

 

/*
    Set the text value of the given element.
    This function assumes this document is defined and not null and has a function getElementById
    Used by: -
*/
function SetText(elementId, text)
{
    // Check input values
    if(IsNullOrUndefined(document)){alert('SetText: Object [document] is null or undefined');}
    if(IsNullOrUndefined(elementId)){alert('SetText: Object [elementId] is null or undefined');}
    if(IsNullOrUndefined(text)){text = '';}

    // Get the given element by id
    var resultGetElementById = document.getElementById(elementId);
    if(IsNullOrUndefined(resultGetElementById)){alert('SetText: Object [resultGetElementById] is null or undefined');}

    // Check if the firstChild is null or undefined
    if(IsNullOrUndefined(resultGetElementById.firstChild))
    {
        // Element does not have a first node, add an textnode.
        resultGetElementById.appendChild(document.createTextNode(text));
    }
    else
    {
        // Element has a first childe node, so replace it's text value.
        resultGetElementById.firstChild.nodeValue = text;
    }
}