Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Thursday, 8 June 2023

Variable Scope in JavaScript: var vs let

In JavaScript, the way variables work in different parts of your code is essential. JavaScript has two keywords for declaring variables "var" and "let". These keywords behave differently in terms of scope. The purpose of this article is to clarify the difference between var and let scoping with an example.

var:

Variables declared with "var" are function-scoped. They are accessible throughout the function regardless of where they are declared within the function.

<!DOCTYPE html>
<html>
<head>
  <title>"var" keyword example</title>
  <script>
    function exampleVar() {
      if (true) {
        var x = 10;
        console.log(x); // Output: 10
      }
      console.log(x); // Output: 10
    }

    exampleVar();
    console.log(x); // Output: ReferenceError: x is not defined
  </script>
</head>
<body>
</body>
</html>

In this example, the variable x declared with var inside the if block is accessible both inside and outside the block because of its function scope.


let:

Variables declared with let are block-scoped. They are accessible only  within the code block in which they are defined, such as within a loop or conditional statement. 

<!DOCTYPE html>
<html>
<head>
  <title>"let" keyword example</title>
  <script>
    function exampleLet() {
      if (true) {
        let y = 20;
        console.log(y); // Output: 20
      }
      console.log(y); // Output: ReferenceError: y is not defined
    }

    exampleLet();
    console.log(y); // Output: ReferenceError: y is not defined
  </script>
</head>
<body>
</body>
</html>

In this example, the variable y declared with let inside the if block is only accessible within that block. Trying to access it outside the block will result in a ReferenceError.

Wednesday, 1 March 2023

Validate RadioButtonList to check if selected using jQuery in .net application

Below is the code for Validating RadioButton List to to check if selected using JavaScript in .net application.

In this code, we use a jQuery selector $('#rdblList input[type=radio]:checked') to select all the radio buttons under the rdblList table that are checked. We then use the .length property to check if the selected radio buttons length is greater than zero. If the length is zero then we display an error message.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" ValidateRequest="false" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head runat="server">
    <title>Validate Radio Button list</title> 
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">   
        function validate() {
            if ($('#rdblList input[type=radio]:checked').length == 0) {
                alert("Please select gender.");
                return false;
            }

        }
    </script>

</head>

<body style="margin: 0;">
    <form id="frmHome" method="post" runat="server">
        <table id="Table1" style="width: 100%" cellspacing="0" cellpadding="0" border="0">
            <tr>
                <td align="center" valign="top" style="width: 100%;">
                    <asp:RadioButtonList runat="server" id="rdblList">
                        <asp:ListItem>Male</asp:ListItem>
                        <asp:ListItem>Female</asp:ListItem>
                    </asp:RadioButtonList>
                    <br />
                    <br />
                    <asp:Button runat="server" ID="btnval" Text="Validate" OnClientClick="return validate();" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>


Validate CheckboxList to select at least one item using jQuery in .net application

Below is the code for Validating Checkbox List to select at least one item using jQuery in .net application.

In this code, we use a jQuery selector $('#chklist input[type=checkbox]:checked') to select all the checkboxes under the chklist table that are checked. We then use the .length property to check if the selected checkboxes length is greater than zero. If the length is zero then we display an error message.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" ValidateRequest="false" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head runat="server">
    <title>Validate Chackbox list</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">    

        function validate() {
            if ($('#chklist input[type=checkbox]:checked').length > 0) {
                    alert("Please select at least one item from checkbox list.");
                    return false;
                }
        }
    </script>

</head>

<body style="margin: 0;">
    <form id="frmHome" method="post" runat="server">
        <table id="Table1" style="width: 100%" cellspacing="0" cellpadding="0" border="0">
            <tr>
                <td align="center" valign="top" style="width: 100%;">

                    <asp:CheckBoxList runat="server" ID="chklist">
                        <asp:ListItem>Validate 1</asp:ListItem>
                        <asp:ListItem>Validate 2</asp:ListItem>
                        <asp:ListItem>Validate 3</asp:ListItem>
                        <asp:ListItem>Validate 4</asp:ListItem>
                    </asp:CheckBoxList>

                    <br />
                    <br />
                    <asp:Button runat="server" ID="btnval" Text="Validate" OnClientClick="return validate();" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

 

 

Validate RadioButtonList to check if selected using JavaScript in .net application

Below is the code for Validating RedioButton List to to check if selected using JavaScript in .net application.
 
In this code, we first select all the radio buttons with the name rdblList using getElementsByName. We then loop through each radio button and check if it is checked. If we find a radio button that is checked, we set the isSelected variable to true and break out of the loop. Finally, we use the isSelected variable to determine whether a radio button is selected or not, and display an error message if no radio button is selected.


-----------------------------------

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" ValidateRequest="false" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head runat="server">
    <title>Validate Radio Button list</title>

    <script type="text/javascript">    

        function validate() {
            var radioButtons = document.getElementsByName('rdblList');
            var isSelected = false;

            for (var i = 0; i < radioButtons.length; i++) {
                if (radioButtons[i].checked) {
                    isSelected = true;
                    break;
                }
            }

            if (isSelected == false) {
                alert("Please select gender.");
                return false;
            }
        }
    </script>

</head>

<body style="margin: 0;">
    <form id="frmHome" method="post" runat="server">
        <table id="Table1" style="width: 100%" cellspacing="0" cellpadding="0" border="0">
            <tr>
                <td align="center" valign="top" style="width: 100%;">

                    <asp:RadioButtonList runat="server" id="rdblList">
                        <asp:ListItem>Male</asp:ListItem>
                        <asp:ListItem>Female</asp:ListItem>
                    </asp:RadioButtonList>

                    <br />
                    <br />
                    <asp:Button runat="server" ID="btnval" Text="Validate" OnClientClick="return validate();" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

Tuesday, 28 February 2023

Validate Checkbox List to select at least one item using JavaScript in .net application

Below is the code for Validating Checkbox List to select at least one item using JavaScript in .net application.

In this code, we first select all the checkboxes under the table with the ID "chklist" using querySelectorAll. We then loop through each checkbox and check if it is checked. If we find a checkbox that is checked, we set the isChecked variable to true and break out of the loop. Finally, we use the isChecked variable to determine whether at least one checkbox is checked or not, and display an error message if no checkbox is checked. 

 
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Test.aspx.vb" Inherits="Test" ValidateRequest="false" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head runat="server">
    <title>Validate Chackbox list</title>

    <script type="text/javascript">    

        function validate() {
            var checkboxes = document.querySelectorAll('#chklist input[type=checkbox]');
            var isChecked = false;

            for (var i = 0; i < checkboxes.length; i++) {
                if (checkboxes[i].checked) {
                    isChecked = true;
                    break;
                }
            }

            if (isChecked == false) {
                alert("Please select at least one item from checkbox list.");
                return false;
            }
        }
    </script>

</head>

<body style="margin: 0;">
    <form id="frmHome" method="post" runat="server">
        <table id="Table1" style="width: 100%" cellspacing="0" cellpadding="0" border="0">
            <tr>
                <td align="center" valign="top" style="width: 100%;">

                    <asp:CheckBoxList runat="server" ID="chklist">
                        <asp:ListItem>Validate 1</asp:ListItem>
                        <asp:ListItem>Validate 2</asp:ListItem>
                        <asp:ListItem>Validate 3</asp:ListItem>
                        <asp:ListItem>Validate 4</asp:ListItem>
                    </asp:CheckBoxList>

                    <br />
                    <br />
                    <asp:Button runat="server" ID="btnval" Text="Validate" OnClientClick="return validate();" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

 

 

Sunday, 31 March 2019

Document Object Model(DOM)

The Document Object Model (DOM) defines the logical structure of documents and the way a document is accessed and manipulated. 

The name "Document Object Model" was chosen because it is an "object model" used in the traditional object-oriented design, documents are modelled using objects, and the model encompasses not only the structure of a document but also the behaviour of a document and the objects of which it is composed. 

In other words, the nodes in the below image do not represent a data structure, they represent objects, which have functions and identity.

Data Object Model(DOM)


With the document object model, JavaScript gets all the power it needs to create dynamic HTML:

1) JavaScript can change all the HTML elements in the page
2) JavaScript can change all the HTML attributes in the page
3) JavaScript can change all the CSS styles in the page
4) JavaScript can remove existing HTML elements and attributes
5) JavaScript can add new HTML elements and attributes
6) JavaScript can react to all existing HTML events in the page
7) JavaScript can create new HTML events in the page

Thursday, 7 June 2018

What is Node.js?

In this post, I will explain What is Node.js and programmers using Node.js.

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js is an open-source command-line tool built for the server-side JavaScript code. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Node.js is used because of various reasons like :
Non-blocking I/O - every I/O call must take a call back, whether it is to retrieve information from disk, network or another process. 
Event-driven means that the server only reacts when an event occurs. This allows the developer to create high performance, highly scalable, “real-time” applications.
Built-in support for protocols like (HTTP, DNS, TLS) 
Low-level - Do not remove functionality present at the POSIX layer. For example, support half-closed TCP connections. 
Powerful bots with useful automated actions and information written in Node.js. All-time running apps for Discord chat which lately people take it as motivation to easily dive into the node world.
Stream everything; never force the buffering of data.

Node.js is used for back-end development, but it is popular as a full-stack and front-end solution as well. It is used primarily to build web applications, but it is a very popular choice for building enterprise applications too. Developers like it because of its versatility, agility and performance. It increases productivity and application performance in a significant way. Since Node.js has a long-term support (LTS) plan that provides security and stability, it's no wonder that huge enterprises constantly add it to their stacks.

Node.js was written by Ryan Dahl in 2009, The initial release of Node.js supported only Linux and Mac OS X. Its development and maintenance were led by Dahl and later sponsored by Joyent. Dahl was inspired to create Node.js after seeing a file upload progress bar on Flickr. The browser did not know how much of the file had been uploaded and had to query the Web server. Dahl desired an easier way.

Applications that can be written using Node.js include, but are not limited to:
1. Static file servers
2. Web Application frameworks
3. REST APIs and Backend Application
4. Real-Time services (Chat, Games etc)
5. Blogs, CMS, Social Applications.
6. Utilities and Tools

Tuesday, 17 October 2017

How to trigger button click event when Enter key pressed in Textbox?

In this post, I will explain How to trigger button click event when Enter key pressed in Textbox?.

To trigger the Button click event when user press Enter Key in Textbox, I have used JavaScript function call with Textbox "onkeypress" event. There is no server-side keypress event for an ASP.Net Textbox. When the user presses any key, JavaScript function check whether it is an Enter key with the help of char code. If pressed key is Enter key then JavaScript function triggers an Asp.Net Button click event. Please go through below code for details.

HTML Code

<%@ Page Language = "C#" AutoEventWireup = "true" CodeBehind = "TriggerButtonClickEvent.aspx.cs" Inherits = "TestApplication.TriggerButtonClickEvent"  %>

<!DOCTYPE html>

<html>
<head>
    <title> How to trigger button click event when Enter key pressed in textbox? </title>

    <script type="text/javascript" language="javascript">

        function TriggerButtonClick(obj, event) {
            var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
            if (keyCode == 13) {
                document.getElementById(obj).click();
                return false;
            }
            else {
                return true;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">

        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

        <asp:Button ID="btnSubmit" runat="server" OnClick = "Button1_Click" />
    </form>
</body>
</html>

C#.Net Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestApplication
{
    public partial class TriggerButtonClickEvent : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            txtName.Attributes.Add("onkeypress", "return TriggerButtonClick('" + btnSubmit.ClientID + "', event)");
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Response.Write("Button click event triggered!");
        }
    }
}




Sunday, 27 August 2017

How to Pass Ampersand (&) as QueryString parameter value in Asp.Net?

In this post, I will explain How to Pass Ampersand (&) as QueryString parameter value in Asp.Net?

In many cases, we need to pass value of variable from one page to another page using QueryString. It generally works fine but when a parameter value contains Ampersand (&) symbol then another page reads wrong parameter value. For example, if suppose Parameter value is "Larsen & Turbo" then another page will read it as "Larsen ".

This happens because generally, Ampersand (&) is used as a separator between 2 parameters in QueryString. You can see the following example,

www.programmingtrends.com?Param1=Google&Param2=India

To solve this problem with An ampersand (&) we can use Server.UrlEncode() function to encode Ampersand (&) in parameter value or we can encode parameter value by replacing '&' with '%26'.

Example:
string Param="Larsen & Turbo";

Response.Redirect("www.programmingtrends.com?param1=" + Server.UrlEncode( Param ));

OR

Response.Redirect("www.programmingtrends.com?param1=" + Param.Replace("&", "%26"));

Thursday, 13 July 2017

Print Panel Content in Asp.Net using JavaScript

In this post, I will explain How to Print Panel Content in Asp.Net using JavaScript.

HTML Code :-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PrintPanel.aspx.cs" Inherits="TestApplication.PrintPanel" %>

<!DOCTYPE html>
<html lang="">
<head>
    <title>Print Panel Content in Asp.Net using JavaScript</title>
    <script type="text/javascript">
        // JavaScript function to print data
        function PrintPanelData() {
            // panel to print data
            var panel = document.getElementById("<%=pnlDetails.ClientID %>");
            // Create a web page with panel content
            var printData = window.open('', '', 'height=500, width=1000');
            printData.document.write('<html><head><title>Panel Data</title>');
            printData.document.write('</head><body >');
            printData.document.write(panel.innerHTML);
            printData.document.write('</body></html>');
            printData.document.close();
            // Open popup window and gives print dialogue box to print content
            setTimeout(function () {
                printData.print();
            }, 20);
            return false;
        }
    </script>
</head>
<body>
    <form runat="server">
        <asp:Panel ID="pnlDetails" runat="server">
            <p style="font-size: 12pt; font-family: 'Times New Roman'">
                Blogger is a blog-publishing service that allows multi-user blogs with time-stamped entries. It was developed by Pyra Labs, which was bought by Google in 2003.
            </p>
            <p style="font-size: 12pt; font-family: 'Times New Roman'">
                Generally, the blogs are hosted by Google at a subdomain of blogspot.com. Blogs can also be hosted in the registered custom domain of the blogger (like www.example.com).
            </p>
            <p style="font-size: 12pt; font-family: 'Times New Roman'">
                [4] A user can have up to 100 blogs per account.
            </p>
        </asp:Panel>
        <br />
        <asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="return PrintPanelData();" />
    </form>
</body>
</html>

Print Panel Content in Asp.Net using JavaScript


Tuesday, 23 May 2017

What is JavaScript?

In this post, I will explain What is JavaScript?

JavaScript is a programming language used along with HTML to make web pages interactive. It runs on the client computer and doesn't require constant downloads from server. JavaScript support is built right into all the major web browsers, including Internet Explorer, Firefox and Safari. To run JavaScript client browser should support JavaScript and have JavaScript enabled. JavaScript enables a web page to do more than just displaying static information. JavaScript is probably involved in displaying timely content updates, interactive maps, animated 2D/3D graphics or scrolling video jukeboxes etc.

A simple example would be if we wish to perform some simple calculations (such as shipping costs) on values that a user puts in a form. We could make the user posts data to the server every time they want an answer, or we could have a button the execute a JavaScript calculation and display the answer to the user.

Advantages of JavaScript-

The advantages of using JavaScript are,
  • Less Server interaction
  • Increased user interactive capabilities
  • Rich User Interfaces
  • Easy to Debug and Test
  • Platform Independence
  • Event-Based Programming

Uses of JavaScript-

Some important uses of JavaScript are,
  • Input Validation
  • Popup Windows
  • Dynamic Contents
  • Mouse Rollover Effects