Search This Blog

Sunday, December 29, 2013



how to redirect visitor from one website to another website using java script
  <script language="javascript" type="text/javascript">
       location.replace("http://www.xyz.com");    
    </script>

How to disable Right click on asp.net website page using JavaScript
<script language=JavaScript>
        var message = "";   
        function clickIE4() {
            if (event.button == 2) {
                alert(message);
                return false;
            }        }
        function clickNS4(e) {
            if (document.layers || document.getElementById && !document.all) {
                if (e.which == 2 || e.which == 3) {
                    alert(message);
                    return false;
                }            }        }
        if (document.layers) {
            document.captureEvents(Event.MOUSEDOWN);
            document.onmousedown = clickNS4;
        }
        else if (document.all && !document.getElementById) {
            document.onmousedown = clickIE4;
        }
        document.oncontextmenu = new Function("return false")
</script>







How to Validate the number range using JavaScript in asp.net
<script type="text/javascript">
       function validateAge() {
            var txtVal = document.getElementById("<%=txtAge.ClientID%>").value;
            if (txtVal >= 18 && txtVal <= 25) {              
                return true;
           }         
            else
                alert('Age must be between 18-25');
                return false;
        }</script>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="javascript:return validateAge();" />

Message box in asp.net website using JavaScript
1 - First Ways
 protected void btnMsg_Click(object sender, EventArgs e)
    {
 ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Record saved Sucessfully');", true);
    }
2- Second Ways
using System.Web.Script.Serialization;
  protected void btnMsg_Click(object sender, EventArgs e)
    {        var message = new JavaScriptSerializer().Serialize("Record saved successfully");
        var script = string.Format("alert({0});", message);
        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "", script, true);
    }
Note: If you want to show message inside UpdatePanel then the above code will not work. Use the below code instead
   ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Record saved successfully');", true);    
 
Server Side Java Script – Pop Up
C#.Net Code to call java script function from code behind file in asp.net

protected void Page_Load(object sender, EventArgs e)
{
    if (!ClientScript.IsStartupScriptRegistered("alert"))
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),
            "alert", "Save Record Successfully”, true);
    }
}

VB.Net Code to call java script function from code behind file in asp.net


If (Not ClientScript.IsStartupScriptRegistered("alert")) Then
    Page.ClientScript.RegisterStartupScript _
 
    (Me.GetType(), "alert", "MyFunction();", True)
End If








Required Field  Validation In Dot Net
<script language="javascript" type="text/javascript">
          function validationCheck() {
              var summary = "";
              summary += isvaliduser();
              summary += isvalidpassword();
              summary += isvalidConfirmpassword();
              summary += isvalidFirstname();
              summary += isvalidLastname();
              summary += isvalidEmail();
              summary += isvalidphoneno();
              summary += isvalidLocation();

              if (summary != "") {
                  alert(summary);
                  return false;
              }
              else {
                  return true;
              }
          }
          function isvaliduser() {
              var id;
              var temp = document.getElementById("<%=txtuser.ClientID %>");
            id = temp.value;
            if (id == "") {
                return ("Please Enter User Name" + "\n");
            }
            else {
                return "";
            }
        }
        function isvalidpassword() {
            var id;
            var temp = document.getElementById("<%=txtpwd.ClientID %>");
            id = temp.value;
            if (id == "") {
                return ("Please enter password" + "\n");
            }
            else {
                return "";
            }
        }
        function isvalidConfirmpassword() {
            var uidpwd;
            var uidcnmpwd;
            var tempcnmpwd = document.getElementById("<%=txtcnmpwd.ClientID %>");
            uidcnmpwd = tempcnmpwd.value;
            var temppwd = document.getElementById("<%=txtpwd.ClientID %>");
            uidpwd = temppwd.value;

            if (uidcnmpwd == "" || uidcnmpwd != uidpwd) {
                return ("Please check and re-enter password to confrim" + "\n");
            }
            else {
                return "";
            }
        }
        function isvalidFirstname() {
            var id;
            var temp = document.getElementById("<%=txtfname.ClientID %>");
            id = temp.value;
            if (id == "") {
                return ("Please enter first name" + "\n");
            }
            else {
                return "";
            }
        }
        function isvalidLastname() {
            var id;
            var temp = document.getElementById("<%=txtlname.ClientID %>");
            id = temp.value;
            if (id == "") {
                return ("Please enter last name" + "\n");
            }
            else {
                return "";
            }
        }
        function isvalidEmail() {
            var id;
            var temp = document.getElementById("<%=txtEmail.ClientID %>");
            id = temp.value;
            var re = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
            if (id == "") {
                return ("Please Enter Email" + "\n");
            }
            else if (re.test(id)) {
                return "";
            }

            else {
                return ("Email should be in the form abc@xyz.com" + "\n");
            }
        }
        function isvalidphoneno() {
            var id;
            var temp = document.getElementById("<%=txtphone.ClientID %>");
            id = temp.value;
            var re;
            re = /^[0-9]+$/;
            var digits = /\d(10)/;
            if (id == "") {
                return ("Please enter phone no" + "\n");
            }
            else if (re.test(id)) {
                return "";
            }

            else {
                return ("Phone no should be digits only" + "\n");
            }
        }
        function isvalidLocation() {
            var id;
            var temp = document.getElementById("<%=txtlocation.ClientID %>");
            id = temp.value;
            if (id == "") {
                return ("Please enter Location" + "\n");
            }
            else {
                return "";
            }
        }
</script>

protected void Page_Load(object sender, EventArgs e)
    {
        btnsubmit.Attributes.Add("onclick""javascript:return validationCheck()");
    }

1-Javascript validation in dot net

<script language="javascript" type="text/javascript">
        function validate()

{

            if (document.getElementById("<%=txtName.ClientID%>").value == "") {
                alert("Name Feild can not be blank");
                document.getElementById("<%=txtName.ClientID%>").focus();
                return false;
            }
            if (document.getElementById("<%=txtEmail.ClientID %>").value == "") {
                alert("Email id can not be blank");
                document.getElementById("<%=txtEmail.ClientID %>").focus();
                return false;
            }

 var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-                \w*)+)$/;
            var emailid = document.getElementById("<%=txtEmail.ClientID %>").value;
            var matchArray = emailid.match(emailPat);
            if (matchArray == null) {
                alert("Your email address seems incorrect. Please try again.");
                document.getElementById("<%=txtEmail.ClientID %>").focus();
                return false;
            }


            if (document.getElementById("<%=txtWebUrl.ClientID %>").value == "") {
                alert("Web URL can not be blank");
                document.getElementById("<%=txtWebUrl.ClientID %>").value = "http://"
                document.getElementById("<%=txtWebUrl.ClientID %>").focus();
                return false;
            }
            var Url = "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"
            var tempURL = document.getElementById("<%=txtWebUrl.ClientID%>").value;
            var matchURL = tempURL.match(Url);
            if (matchURL == null) {
                alert("Web URL does not look valid");
                document.getElementById("<%=txtWebUrl.ClientID %>").focus();
                return false;
            }

            if (document.getElementById("<%=txtZip.ClientID%>").value == "") {
                alert("Zip Code is not valid");
                document.getElementById("<%=txtZip.ClientID%>").focus();
                return false;
            }
            var digits = "0123456789";
            var temp;
            for (var i = 0; i < document.getElementById("<%=txtZip.ClientID >").value.length;i++) {
                temp = document.getElementById("<%=txtZip.ClientID%>").value.substring(i, i + 1);
                if (digits.indexOf(temp) == -1) {
                    alert("Please enter correct zip code");
                    document.getElementById("<%=txtZip.ClientID%>").focus();
                    return false;
                }
            }            return true;        }</script>
<asp:Button ID="btnsubmit" OnClientClick=" return validate()" runat="server" Text="Submit" />






1-Enable Disable Textboxes based on CheckBox using JavaScript
<script type="text/javascript">
        window.onload = function() {
            var check = document.getElementById("<%=checkbox1.ClientID %>");
            check.onchange = function() {
                if (this.checked == true)
                    document.getElementById("<%=textbox1.ClientID %>").disabled = false;
                else
                    document.getElementById("<%=textbox1.ClientID %>").disabled = true;
            };
        };
</script> 
 <asp:checkbox checked="false" id="checkbox1" runat="server"  />
        <asp:textbox id="textbox1" enabled="false" text="Test" runat="server" />
·         How To Disable Textbox After Checkbox Checked In Datagridview/DataGrid(Edit Template /Template Field)
·         <script language="javascript" type="text/javascript">
·         function GetCheckStatus() {
·         var srcControlId = event.srcElement.id;
·         var targetControlId = event.srcElement.id.replace('chkThirdParty', 'txtThirdParty');
·         if (document.getElementById(srcControlId).checked)
·         document.getElementById(targetControlId).disabled = false;
·         else
·         document.getElementById(targetControlId).disabled = true;
·         }
·         </script>
·         Used---
·          
·         <EditItemTemplate>
<asp:CheckBox id="chkThirdParty" runat="server" onclick="GetCheckStatus()" checked='<%# Iif(DataBinder.Eval(Container, "DataItem.IsThirdParty") Is System.DBNull.Value, false, DataBinder.Eval(Container, "DataItem.IsThirdParty")) %>'></asp:CheckBox>
<asp:TextBox id="txtThirdParty" runat="server"  Width="130px" CssClass="inputbox" MaxLength="100" Text='<%# DataBinder.Eval(Container, "DataItem.ThirdPartyName") %>' ></asp:TextBox>
·         </EditItemTemplate>
2- Text Box Only Numbers allow  By JavaSript
<script type = "text/javascript" language = "javascript">
  
function numeralsOnly(evt)
{
           evt = (evt) ? evt : event;
           var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ?                       evt.keyCode : ((evt.which) ? evt.which : 0));
           if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode != 46)) {
              return false;
           }
           return true;
       }
 </script>

<asp:TextBox ID="txtRRate" runat="server" onkeypress="return numeralsOnly(event)"  Width="30px" TabIndex="8"  MaxLength="5"></asp:TextBox>
3- A Text Box Allow Only Numbers ( ,) (+) and (-)  For Mobile Validate
<script type="text/javascript">
        var specialKey = new Array();
        specialKey.push(8); //Backspace
        specialKey.push(43); //+ Plus
        specialKey.push(44); //,comma
        specialKey.push(45); //- hyphen
        function GeneralNumber(e) {
            var keyCode = e.which ? e.which : e.keyCode
            var General = ((keyCode >= 48 && keyCode <= 57) ||                         specialKey.indexOf(keyCode) != -1);
            return General;
        }
    </script>

<asp:TextBox ID="txtRPMContactNO" Width="150px" runat="server" MaxLength="50" TabIndex="25" onkeypress="return GeneralNumber(event);" ondrop="return false;" onpaste="return false;"></asp:TextBox>


4-A Text Box Allow Only Number and (:) Using Java script
<script type="text/javascript">
        var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        specialKeys.push(58); //: Colon
        function IsFTHTime(e) {
            var keyCode = e.which ? e.which : e.keyCode
            var FTH = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
            //            document.getElementById("errorFTH").style.display = FTH ? "none" : "inline";
            return FTH;
        }
   </script>

<asp:TextBox ID="txtFTH" Width="50px" runat="server" onkeypress="return IsFTHTime(event);"ondrop="return false;" onpaste="return false;" MaxLength="5" Style='text-align: right' TabIndex="10"></asp:TextBox>

5- A text Box Allow Only Dot (.) and Number  And Return in Span
<script type="text/javascript">
        var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        specialKeys.push(46); //. Dot
        function IsNumeric(e) {
            var keyCode = e.which ? e.which : e.keyCode
            var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
            document.getElementById("error").style.display = ret ? "none" : "inline";
            return ret;
        }
    </script>

<asp:TextBox ID="txtFTH" Width="50px" runat="server" onkeypress="return IsFTHTime(event);"ondrop="return false;" onpaste="return false;" MaxLength="5" Style='text-align: right' TabIndex="10"></asp:TextBox>
 <span id="error" style="color: Red; display: none">* Only Digit are allowed as input. </span>




6-Stop multiline TextBox Character( Max Length  )
<script type="text/javascript"  language="javascript">

        // Keep user from entering more than maxLength characters
        function textboxMultilineMaxNumberdoKeypress(control) {
            maxLength = control.attributes["maxLength"].value;
            value = control.value;
            if (maxLength && value.length > maxLength - 1) {
                event.returnValue = false;
                maxLength = parseInt(maxLength);
            }
        }
        // Cancel default behavior

        function textboxMultilineMaxNumberdoBeforePaste(control) {
            maxLength = control.attributes["maxLength"].value;
            if (maxLength) {
                event.returnValue = true;
            }
        }
        // Cancel default behavior and create a new paste routine

        function textboxMultilineMaxNumberdoPaste(control) {
            maxLength = control.attributes["maxLength"].value;
            value = control.value;
            if (maxLength) {
                event.returnValue = false;
                maxLength = parseInt(maxLength);
                var oTR = control.document.selection.createRange();
                var iInsertLength = maxLength - value.length + oTR.text.length;
                var sData = window.clipboardData.getData("Text").substr(0, iInsertLength);
                oTR.text = sData;
            }
        }
    </script>

 <asp:TextBox ID="TextBox1" runat="server" Width="362px" TabIndex="15" Height="80px"
  CssClass="noResize" Rows="4" TextMode="MultiLine" MaxLength="10" onbeforepaste="textboxMultilineMaxNumberdoBeforePaste(this);"
 onkeypress="textboxMultilineMaxNumberdoKeypress(this);" onpaste="textboxMultilineMaxNumberdoPaste(this);"></asp:TextBo

Add Code Page Load Event-

 txtDescription.Attributes.Add("maxLength", txtDescription.MaxLength.ToString());


Find Control Using Javascript


// To Find Controls using Javascript
    // To Find Gridview or Other Data Controls
        var datalist = document.getElementById("GdvPrice");

    // To Find Input Elements like Textbox
        var sp = datalist.getElementsByTagName("input");

    // To Find Elements Like Label
         var Label = datalist.getElementsByTagName("span");

    // To Find Elements Like DropDownList
         var wp = datalist.getElementsByTagName("select");



// To Find Controls using Javascript on click of linkbutton in gridview
   
    //Call The below function on clientclick event of linkbutton
    function Sunil(lnk)
         {
            var row = lnk.parentNode.parentNode;           
            var rowIndex = row.rowIndex - 1; 

    //To find label  value
            var ProductId = row.cells[0].children[0].value;
            var ProductName = row.cells[1].getElementsByTagName("span")[0].innerHTML;

   //To find dropdownlist value       
           var qty = row.cells[7].getElementsByTagName("select")[0];
           qty=qty.options[qty.selectedIndex].text;
     
}




Email validation using javascript

function EmailValidate() {

var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.getElementById("txtEmail").value;
if (reg.test(address) == false) {

alert('Invalid Email Address');
return false;
}
}


asp:TextBox ID="txtEmail" runat="server">

asp:Button ID="Button1" runat="server" Text="Validate" OnClientClick="return Validate();"

How to allow only numbers into textbox using javascript, asp.net , Allow only numbers validation using javascript

function numbersonly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode
if (unicode != 8) { //if the key isn't the backspace key (which we should allow)
if (unicode < 48 || unicode > 57) //if not a number
return false //disable key press
}
}



asp:TextBox ID="tbxBkgRefNo" runat="server" onkeypress="return numbersonly(event);"



Date difference in Javascript using asp.net and Calculating Duration Between Two Dates in Years, Months and Days

Use below javascript function to

1) validate the date difference in asp.net
2) difference (number of days, months, years) between two dates.


function validate(ArrivalDate, DepartureDate )
{
var ArrivalDtValue = "15/02/2011"; // ArrivalDate
var DepartureDtValue = "16/02/2011"; // DepartureDate

var currentTime = new Date();
var month = currentTime.getMonth();
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currentDt = day + "/" + month + "/" + year;

var ArrDt = getDateObject(ArrivalDtValue, "/");
var DeparDt = getDateObject(DepartureDtValue, "/");
var CurDt = new Date();

//Total time for one day
var one_day = 1000 * 60 * 60 * 24;
//Here we need to split the inputed dates to convert them into standard format
//for furter execution
var x = ArrivalDtValue.split("/");
var y = DepartureDtValue.split("/");
//date format(Fullyear,month,date)
var ArrivalDate = new Date(x[2], (x[1] - 1), x[0]);
var DepartureDate = new Date(y[2], (y[1] - 1), y[0]);
var CurrentDate = new Date(year, month, day);
var month1 = x[1] - 1;
var month2 = y[1] - 1;

//Calculate difference between the two dates, and convert to days
var ArrivaldiffDays = Math.abs((CurrentDate.getTime() - ArrivalDate.getTime()) / (one_day));
var DeparturediffDays = Math.abs((CurrentDate.getTime() - DepartureDate.getTime()) / (one_day));


if (ArrDt > DeparDt) {
        alert("Departure date should not be less than Arrival date");
        return false;
}
else if (ArrivalDtValue == DepartureDtValue) {
      alert("Arrival date and Departure date should not be same");
      return false;
}
else if (ArrDt < CurrentDate)
{
      alert("Arrival date should not be less than current date");
      return false;
}
else if (DeparDt < CurrentDate)
{
     alert("Departure date should not be less than current date");
     return false;
}
else
{
     return true;
}
}


function getDateObject(dateString, dateSeperator) {
//This function return a date object after accepting
//a date string ans dateseparator as arguments
var curValue = dateString;
var sepChar = dateSeperator;
var curPos = 0;
var cDate, cMonth, cYear;

//extract day portion
curPos = dateString.indexOf(sepChar);
cDate = dateString.substring(0, curPos);

//extract month portion
endPos = dateString.indexOf(sepChar, curPos + 1);
cMonth = dateString.substring(curPos + 1, endPos);

//extract year portion
curPos = endPos;
endPos = curPos + 5;
cYear = curValue.substring(curPos + 1, endPos);

//Create Date Object
dtObject = new Date(cYear, cMonth - 1, cDate);
//alert(dtObject);
return dtObject;
}


Date validation using Javascript in asp.net
function validate() {
var oInput1 = document.getElementById("datepicker_Control");

if (isValidDate(oInput1))
{
//proceed code
}
else
{
// alert message
}

}



function isValidDate(field) {
var checkstr = "0123456789";
var DateField = field;
var Datevalue = "";
var DateTemp = "";
var seperator = ",";
var day;
var month;
var year;
var leap = 0;
var err = 0;
var i;
err = 0;
DateValue = DateField;
/* Delete all chars except 0..9 */
for (i = 0; i < DateValue.length; i++) { if (checkstr.indexOf(DateValue.substr(i, 1)) >= 0) {
DateTemp = DateTemp + DateValue.substr(i, 1);
}
}
DateValue = DateTemp;
/* Always change date to 8 digits - string*/
/* if year is entered as 2-digit / always assume 20xx */
if (DateValue.length == 6) {
DateValue = DateValue.substr(0, 4) + '20' + DateValue.substr(4, 2);
}
if (DateValue.length != 8) {
err = 19;
}
/* year is wrong if year = 0000 */
year = DateValue.substr(4, 4);
if (year == 0) {
err = 20;
}
/* Validation of month*/
month = DateValue.substr(2, 2);
if ((month < 1) || (month > 12)) {
err = 21;
}
/* Validation of day*/
day = DateValue.substr(0, 2);
if (day < 1) { err = 22; } /* Validation leap-year / february / day */ if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) { leap = 1; } if ((month == 2) && (leap == 1) && (day > 29)) {
err = 23;
}
if ((month == 2) && (leap != 1) && (day > 28)) {
err = 24;
}
/* Validation of other months */
if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
err = 25;
}
if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
err = 26;
}
/* if 00 ist entered, no error, deleting the entry */
if ((day == 0) && (month == 0) && (year == 00)) {
err = 0; day = ""; month = ""; year = ""; seperator = "";
}
/* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
if (err == 0) {
DateField.value = day + seperator + month + seperator + year;
}
/* Error-message if err != 0 */
else {
return false;
}
return true;
}

Confirmation box from code behind (server side) c# using modalpopup ajax control

Confirmation box from code behind c# using modalpopup ajax control

<%@ Page Language="C#" AutoEventWireup="true"CodeFile="ConfirmPopUp.aspx.cs" Inherits="ConfirmPopUp" %>

<%@ Register Assembly="AjaxControlToolkit"Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
        .modalBackground
        {
            background-colorGray;
            filteralpha(opacity=70);
            opacity0.7;
        }
       
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"EnablePartialRendering="true">
    </asp:ScriptManager>
    <div>
        <asp:HiddenField ID="HiddenField1" runat="server"Value="2" />       
        <asp:Button ID="Button4" runat="server" Text="Validate and Open POPUP" OnClick="Button4_Click" /><br />
        <cc1:ModalPopupExtender id="ModalPopupExtender1"runat="server" targetcontrolid="Button1"
            popupcontrolid="PnlModal"backgroundcssclass="modalBackground">       </cc1:ModalPopupExtender>
        <asp:Button ID="Button1" runat="server" Text="Button"Style="visibilityhidden" />
        <asp:Panel ID="PnlModal" runat="server" Width="450px"style="display:none;                                                                    background-color#ffffdd;
border-width3px;
border-stylesolid;
border-colorGray;
padding3px;
height:75px;
text-align:center">
            Are you sure want to Process?<br />
            <asp:Button ID="Button2" runat="server" Text="Yes"OnClick="Button2_Click" />
            <asp:Button ID="Button3" runat="server" Text="No"OnClick="Button3_Click" />
        </asp:Panel>
    </div>
    </form>
</body>
</html>


Code Behind:
using System;

public partial class ConfirmPopUp : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        if (HiddenField1.Value == "2")
        {
            ModalPopupExtender1.Show();
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {      
        //Your Processing code placed here       
        ModalPopupExtender1.Hide();
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        ModalPopupExtender1.Hide();
    }
}

How To: Stop the ModalPopup Flicker
In above code PnlModal having the style="display:none;” to avoid flickering of confirmation box when page load happens
<asp:Panel ID="PnlModal" runat="server" Width="450px"style="display:none;”                                                                   

How To: Avoid “Object Required” javascript error from ScriptResource.axd when popup is shown
Don’t use PnlModal.Visible = false/true; from code behind to hide/show the popup, this is not required why because ModalPopupExtender will take care this behaviour.



C# var Vs Javascript var

Difference between C# var and Javascript var 


C#

var i = 10; // implicitly typed
int i = 10; //explicitly typed

//Initialization is mandatory
var a = 10;
//Allowed
a = 13;
//Not Allowed
a = "string";

By using above example we can say C# var is strongly typed, but inferred from whatever the value is being assigned.

Javascript

   <script type="text/javascript">
        var a = "stringValue";
              a = 567;
              a= "2ndString"; // allowed
    </script>

How to raise client side (javascript) or server side (code behind) messages in asp.net


Use below code to raise messages from javascript and code behind.

.ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RaisingMessages.aspx.cs"
    Inherits="RaisingMessages" %>

<!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>Validation</title>

    <script type="text/javascript">

        function ValidatePage() {
            var fName = document.getElementById("txtFirstName");
            var lName = document.getElementById("txtLastName");

            if (fName.value == "") {
                //client side alert message
                alert('First Name should not be empty');
                return false;
            }       
            return true;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <asp:Label ID="lblFirstName" runat="server" Text="First Name"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblLastName" runat="server" Text="Last Name"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSubmit" runat="server" Text="Submit"
                    OnClientClick="return ValidatePage();" onclick="btnSubmit_Click" />
            </td>
        </tr>   
    </table>
    </form>
</body>
</html>

.ASPX.CS


using System;
using System.Web.UI;

public partial class RaisingMessages : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtLastName.Text.Trim()))
        {        
            string script = "alert('Last Name should not be empty')";
            Type csType = GetType();
            // Server side alert message
            ScriptManager.RegisterStartupScript(Page, csType, "popuscript", script, true);
            return;
        }
    }
}

Restrict to 2 decimal places in keypress of a text box

<asp:TextBox ID="txtngo" MaxLength="10" onkeypress="return AllowDecimalNo2Place(event);" runat="server" Width="48%" ToolTip="Numeric/decimal only"></asp:TextBox>
function AllowDecimalNo2Place(event)
        {
             
            // Code added by Ram Vinay Singh

           if ((event.which != 46 || document.getElementById('<%=txtngo.ClientID%>').value.indexOf('.') != -1) &&
           ((event.which < 48 || event.which > 57) &&
             (event.which != 0 && event.which != 8))) {
                        event.preventDefault();
                    }

            var text = document.getElementById('<%=txtAvPrice.ClientID%>').value;

                    if ((text.indexOf('.') != -1) &&
                      (text.substring(text.indexOf('.')).length > 2) &&
                      (event.which != 0 && event.which != 8) &&
                      (document.getElementById('<%=txtAvePrice.ClientID%>').selectionStart >= text.length - 2)) {
                        event.preventDefault();
                    }
         
         }

Wednesday, August 17, 2011


How To: Prevent Cross-Site Scripting in ASP.NET

Applies To

  • ASP.NET version 1.1
  • ASP.NET version 2.0

Summary

This How To shows how you can help protect your ASP.NET applications from cross-site scripting attacks by using proper input validation techniques and by encoding the output. It also describes a number of other protection mechanisms that you can use in addition to these two main countermeasures.
Cross-site scripting (XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. Common vulnerabilities that make your Web applications susceptible to cross-site scripting attacks include failing to properly validate input, failing to encode output, and trusting the data retrieved from a shared database. To protect your application against cross-site scripting attacks, assume that all input is malicious. Constrain and validate all input. Encode all output that could, potentially, include HTML characters. This includes data read from files and databases.

Objectives

  • Understand the common cross-site scripting vulnerabilities in Web page validation.
  • Apply countermeasures for cross-site scripting attacks.
  • Constrain input by using regular expressions, type checks, and ASP.NET validator controls.
  • Constrain output to ensure the browser does not execute HTML tags that contain script code.
  • Review potentially dangerous HTML tags and attributes and evaluate countermeasures.

Overview

Cross-site scripting attacks exploit vulnerabilities in Web page validation by injecting client-side script code. The script code embeds itself in response data, which is sent back to an unsuspecting user. The user's browser then runs the script code. Because the browser downloads the script code from a trusted site, the browser has no way of recognizing that the code is not legitimate, and Microsoft Internet Explorer security zones provide no defense. Cross-site scripting attacks also work over HTTP and HTTPS (SSL) connections.
One of the most serious examples of a cross-site scripting attack occurs when an attacker writes script to retrieve the authentication cookie that provides access to a trusted site and then posts the cookie to a Web address known to the attacker. This enables the attacker to spoof the legitimate user's identity and gain illicit access to the Web site.
Common vulnerabilities that make your Web application susceptible to cross-site scripting attacks include:
  • Failing to constrain and validate input.
  • Failing to encode output.
  • Trusting data retrieved from a shared database.

Guidelines

The two most important countermeasures to prevent cross-site scripting attacks are to:
  • Constrain input.
  • Encode output.

Constrain Input

Start by assuming that all input is malicious. Validate input type, length, format, and range.
  • To constrain input supplied through server controls, use ASP.NET validator controls such as RegularExpressionValidator and RangeValidator.
  • To constrain input supplied through client-side HTML input controls or input from other sources such as query strings or cookies, use theSystem.Text.RegularExpressions.Regex class in your server-side code to check for expected using regular expressions.
  • To validate types such as integers, doubles, dates, and currency amounts, convert the input data to the equivalent .NET Framework data type and handle any resulting conversion errors.
For more information about and examples of how to constrain input, see How To: Protect From Injection Attacks in ASP.NET.

Encode Output

Use the HttpUtility.HtmlEncode method to encode output if it contains input from the user or from other sources such as databases. HtmlEncode replaces characters that have special meaning in HTML-to-HTML variables that represent those characters. For example, < is replaced with &lt; and " is replaced with &quot;. Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML.
Similarly, use HttpUtility.UrlEncode to encode output URLs if they are constructed from input.

Summary of Steps

To prevent cross-site scripting, perform the following steps:
  • Step 1. Check that ASP.NET request validation is enabled.
  • Step 2. Review ASP.NET code that generates HTML output.
  • Step 3. Determine whether HTML output includes input parameters.
  • Step 4. Review potentially dangerous HTML tags and attributes.
  • Step 5. Evaluate countermeasures.

Step 1. Check That ASP.NET Request Validation Is Enabled

By default, request validation is enabled in Machine.config. Verify that request validation is currently enabled in your server's Machine.config file and that your application does not override this setting in its Web.config file. Check that validateRequest is set to true as shown in the following code example.

<system.web><pages buffer="true" validateRequest="true" /></system.web> 
 
You can disable request validation on a page-by-page basis. Check that your pages do not disable this feature unless necessary. For example, you may need to disable this feature for a page if it contains a free-format, rich-text entry field designed to accept a range of HTML characters as input. For more information about how to safely handle this type of page, see Step 5. Evaluate Countermeasures.
To test that ASP.NET request validation is enabled
  1. Create an ASP.NET page that disables request validation. To do this, setValidateRequest="false", as shown in the following code example.
    <%@ Page Language="C#" ValidateRequest="false" %>
    <html>
     <script runat="server">
      void btnSubmit_Click(Object sender, EventArgs e)
      {
        // If ValidateRequest is false, then 'hello' is displayed
        // If ValidateRequest is true, then ASP.NET returns an exception
        Response.Write(txtString.Text);
      }
     </script>
     <body>
      <form id="form1" runat="server">
        <asp:TextBox id="txtString" runat="server" 
                     Text="<script>alert('hello');</script>" />
        <asp:Button id="btnSubmit" runat="server"   
                    OnClick="btnSubmit_Click" 
                    Text="Submit" />
      </form>
     </body>
    </html>
      
  2. Run the page. It displays Hello in a message box because the script in txtString is passed through and rendered as client-side script in your browser.
  3. Set ValidateRequest="true" or remove the ValidateRequest page attribute and browse to the page again. Verify that the following error message is displayed.
    A potentially dangerous Request.Form value was detected from the client (txtString="<script>alert('hello...").
      
    This indicates that ASP.NET request validation is active and has rejected the input because it includes potentially dangerous HTML characters.
    Note   Do not rely on ASP.NET request validation. Treat it as an extra precautionary measure in addition to your own input validation.

Step 2. Review ASP.NET Code That Generates HTML Output

ASP.NET writes HTML as output in two ways, as shown in the following code examples.
Response.Write
<% =
  
Search your pages to locate where HTML and URL output is returned to the client.

Step 3. Determine Whether HTML Output Includes Input Parameters

Analyze your design and your page code to determine whether the output includes any input parameters. These parameters can come from a variety of sources. The following list includes common input sources:
  • Form fields, such as the following.
    Response.Write(name.Text);
    Response.Write(Request.Form["name"]);
    Query Strings
    Response.Write(Request.QueryString["name"]);
      
  • Query strings, such as the following:
    Response.Write(Request.QueryString["username"]);
      
  • Databases and data access methods, such as the following:
    SqlDataReader reader = cmd.ExecuteReader();
    Response.Write(reader.GetString(1));
      
    Be particularly careful with data read from a database if it is shared by other applications.
  • Cookie collection, such as the following:
    Response.Write(
    Request.Cookies["name"].Values["name"]);
      
  • Session and application variables, such as the following:
    Response.Write(Session["name"]);
    Response.Write(Application["name"]);
      
In addition to source code analysis, you can also perform a simple test by typing text such as "XYZ" in form fields and testing the output. If the browser displays "XYZ" or if you see "XYZ" when you view the source of the HTML, your Web application is vulnerable to cross-site scripting.
To see something more dynamic, inject <script>alert('hello');</script> through an input field. This technique might not work in all cases because it depends on how the input is used to generate the output.

Step 4. Review Potentially Dangerous HTML Tags and Attributes

If you dynamically create HTML tags and construct tag attributes with potentially unsafe input, make sure you HTML-encode the tag attributes before writing them out.
The following .aspx page shows how you can write HTML directly to the return page by using the <asp:Literal> control. The code takes user input of a color name, inserts it into the HTML sent back, and displays text in the color entered. The page uses HtmlEncode to ensure the inserted text is safe.
<%@ Page Language="C#" AutoEventWireup="true"%>

<html>
  <form id="form1" runat="server">
    <div>
      Color:&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
      <asp:Button ID="Button1" runat="server" Text="Show color" 
         OnClick="Button1_Click" /><br />
      <asp:Literal ID="Literal1" runat="server"></asp:Literal>
    </div>
  </form>
</html>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
  {
    protected void Button1_Click(object sender, EventArgs e)
    {
      Literal1.Text = @"<span style=""color:" 
        + Server.HtmlEncode(TextBox1.Text)
        + @""">Color example</span>";
    }           
  }
</Script>
  

Potentially Dangerous HTML Tags

While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code:
  • <applet>
  • <body>
  • <embed>
  • <frame>
  • <script>
  • <frameset>
  • <html>
  • <iframe>
  • <img>
  • <style>
  • <layer>
  • <link>
  • <ilayer>
  • <meta>
  • <object>
An attacker can use HTML attributes such as srclowsrcstyle, and href in conjunction with the preceding tags to inject cross-site scripting. For example, the src attribute of the <img> tag can be a source of injection, as shown in the following examples.
<img src="javascript:alert('hello');">
<img src="java&#010;script:alert('hello');">
<img src="java&#X0A;script:alert('hello');">
  
An attacker can also use the <style> tag to inject a script by changing the MIME type as shown in the following.
<style TYPE="text/javascript">
  alert('hello');
</style>
  

Step 5. Evaluate Countermeasures

When you find ASP.NET code that generates HTML using some input, you need to evaluate appropriate countermeasures for your specific application. Countermeasures include:
  • Encode HTML output.
  • Encode URL output.
  • Filter user input.

Encode HTML Output

If you write text output to a Web page and you do not know if the text contains HTML special characters (such as <, >, and &), pre-process the text by using theHttpUtility.HtmlEncode method as shown in the following code example. Do this if the text came from user input, a database, or a local file.
Response.Write(HttpUtility.HtmlEncode(Request.Form["name"]));
  
Do not substitute encoding output for checking that input is well-formed and correct. Use it as an additional security precaution.

Encode URL Output

If you return URL strings that contain input to the client, use the HttpUtility.UrlEncodemethod to encode these URL strings as shown in the following code example.
Response.Write(HttpUtility.UrlEncode(urlString));
  

Filter User Input

If you have pages that need to accept a range of HTML elements, for example through some kind of rich text input field, you must disable ASP.NET request validation for the page. If you have several pages that do this, create a filter that allows only the HTML elements that you want to accept. A common practice is to restrict formatting to safe HTML elements such as bold (<b>) and italic (<i>).
To safely allow restricted HTML input
  1. Disable ASP.NET request validation by the adding the ValidateRequest="false"attribute to the @ Page directive.
  2. Encode the string input with the HtmlEncode method.
  3. Use a StringBuilder and call its Replace method to selectively remove the encoding on the HTML elements that you want to permit.
The following .aspx page code shows this approach. The page disables ASP.NET request validation by setting ValidateRequest="false". It HTML-encodes the input and then selectively allows the <b> and <i> HTML elements to support simple text formatting.
<%@ Page Language="C#" ValidateRequest="false"%>

<script runat="server">

  void submitBtn_Click(object sender, EventArgs e)
  {
    // Encode the string input
    StringBuilder sb = new StringBuilder(
                            HttpUtility.HtmlEncode(htmlInputTxt.Text));
    // Selectively allow  <b> and <i>
    sb.Replace("&lt;b&gt;", "<b>");
    sb.Replace("&lt;/b&gt;", "");
    sb.Replace("&lt;i&gt;", "<i>");
    sb.Replace("&lt;/i&gt;", "");
    Response.Write(sb.ToString());
  }
</script>

<html>
  <body>
    <form id="form1" runat="server">
      <div>
        <asp:TextBox ID="htmlInputTxt" Runat="server" 
                     TextMode="MultiLine" Width="318px"
                     Height="168px"></asp:TextBox>
        <asp:Button ID="submitBtn" Runat="server" 
                     Text="Submit" OnClick="submitBtn_Click" />
      </div>
    </form>
  </body>
</html>
  

Additional Considerations

In addition to the techniques discussed previously in this How To, use the following countermeasures as further safe guards to prevent cross-site scripting:
  • Set the correct character encoding.
  • Do not rely on input sanitization.
  • Use the HttpOnly cookie option.
  • Use the <frame> security attribute.
  • Use the innerText property instead of innerHTML.

Set the Correct Character Encoding

To successfully restrict valid data for your Web pages, you should limit the ways in which the input data can be represented. This prevents malicious users from using canonicalization and multi-byte escape sequences to trick your input validation routines. A multi-byte escape sequence attack is a subtle manipulation that uses the fact that character encodings, such as uniform translation format-8 (UTF-8), use multi-byte sequences to represent non-ASCII characters. Some byte sequences are not legitimate UTF-8, but they may be accepted by some UTF-8 decoders, thus providing an exploitable security hole.
ASP.NET allows you to specify the character set at the page level or at the application level by using the <globalization> element in the Web.config file. The following code examples show both approaches and use the ISO-8859-1 character encoding, which is the default in early versions of HTML and HTTP.
To set the character encoding at the page level, use the <meta> element or theResponseEncoding page-level attribute as follows:

<meta http-equiv="Content Type" 
      content="text/html; charset=ISO-8859-1" />

OR
<% @ Page ResponseEncoding="iso-8859-1" %>
  
To set the character encoding in the Web.config file, use the following configuration.
 
<configuration>
   <system.web>
      <globalization 
         requestEncoding="iso-8859-1"
         responseEncoding="iso-8859-1"/>
   </system.web>
</configuration>
  

Validating Unicode Characters

Use the following code to validate Unicode characters in a page.
using System.Text.RegularExpressions;
. . .

public class WebForm1 : System.Web.UI.Page
{
  private void Page_Load(object sender, System.EventArgs e)
  {
    // Name must contain between 1 and 40 alphanumeric characters
    // and (optionally) special characters such as apostrophes  
    // for names such as O'Dell

    if (!Regex.IsMatch(Request.Form["name"],
               @"^[\p{L}\p{Zs}\p{Lu}\p{Ll}\']{1,40}$"))
      throw new ArgumentException("Invalid name parameter");

    // Use individual regular expressions to validate other parameters
    . . .
  }
}
  
The following explains the regular expression shown in the preceding code:
  • ^ means start looking at this position.
  • \p{ ..} matches any character in the named character class specified by {..}.
  • {L} performs a left-to-right match.
  • {Lu} performs a match of uppercase.
  • {Ll} performs a match of lowercase.
  • {Zs} matches separator and space.
  • 'matches apostrophe.
  • {1,40} specifies the number of characters: no less than 1 and no more than 40.
  • $ means stop looking at this position.

Do Not Rely on Input Sanitization

A common practice is for code to attempt to sanitize input by filtering out known unsafe characters. Do not rely on this approach because malicious users can usually find an alternative means of bypassing your validation. Instead, your code should check for known secure, safe input. Table 1 shows various safe ways to represent some common characters.

Table 1: Character Representation
CharactersDecimalHexadecimalHTML Character SetUnicode
(double quotation marks)&#34&#x22&quot;\u0022
(single quotation mark)&#39&#x27&apos;\u0027
& (ampersand)&#38&#x26&amp;\u0026
< (less than)&#60&#x3C&lt;\u003c
> (greater than)&#62&#x3E&gt;\u003e

 

Use the HttpOnly Cookie Option

Internet Explorer 6 Service Pack 1 and later supports an HttpOnly cookie attribute, which prevents client-side scripts from accessing a cookie from the document.cookie property. Instead, the script returns an empty string. The cookie is still sent to the server whenever the user browses to a Web site in the current domain.
Note   Web browsers that do not support the HttpOnly cookie attribute either ignore the cookie or ignore the attribute, which means that it is still subject to cross-site scripting attacks.
The System.Net.Cookie class in Microsoft .NET Framework version 2.0 supports anHttpOnly property. The HttpOnly property is always set to true by Forms authentication.
Earlier versions of the .NET Framework (versions 1.0 and 1.1) require that you add code similar to the following to the Application_EndRequest event handler in your application Global.asax file to explicitly set the HttpOnly attribute.

protected void Application_EndRequest(Object sender, EventArgs e) 
{
  string authCookie = FormsAuthentication.FormsCookieName;
  foreach (string sCookie in Response.Cookies) 
  {
    // Just set the HttpOnly attribute on the Forms 
    // authentication cookie. Skip this check to set the attribute 
    // on all cookies in the collection

    if (sCookie.Equals(authCookie))
    { 
      // Force HttpOnly to be added to the cookie header
      Response.Cookies[sCookie].Path += ";HttpOnly";
    }
  }
}
  

Use the <frame> Security Attribute

Internet Explorer 6 and later support a new security attribute for the <frame> and <iframe> elements. You can use the security attribute to apply the user's Restricted Sites Internet Explorer security zone settings to an individual frame or iframe. By default, the Restricted Sites zone does not support script execution.
If you use the security attribute, it must be set to "restricted" as shown in the following.
<frame security="restricted" src="http://www.somesite.com/somepage.htm"></frame>
  

Use the innerText Property Instead of innerHTML

If you use the innerHTML property to build a page and the HTML is based on potentially untrusted input, you must use HtmlEncode to make it safe. To avoid having to remember to do this, use innerText instead. The innerText property renders content safe and ensures that scripts are not executed.
The following example shows this approach for two HTML <span> controls. The code in thePage_Load method sets the text displayed in the Welcome1 <span> element using theinnerText property, so HTML-encoding is unnecessary. The code sets the text in theWelcome2 <span> element by using the innerHtml property; therefore, you mustHtmlEncode it first to make it safe.
<%@ Page Language="C#" AutoEventWireup="true"%>

<html>
  <body>
    <span id="Welcome1" runat="server"> </span>
    <span id="Welcome2" runat="server"> </span>
  </body>
</html>

<script runat="server">
  private void Page_Load(Object Src, EventArgs e)
  {
    // Using InnerText renders the content safe–no need to HtmlEncode
    Welcome1.InnerText = "Hello, " + User.Identity.Name;

    // Using InnerHtml requires the use of HtmlEncode to make it safe
    Welcome2.InnerHtml = "Hello, " + 
                        Server.HtmlEncode(User.Identity.Name);
  }
</Script>
  

Latest jQuery interview questions and answers

Q1. What is jQuery?

Ans: jQuery is fast, lightweight and feature-rich client side JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. It is one of the most popular client side library and as per a survey it runs on every second website.

Q2. Why do we use jQuery?

Ans: Due to following advantages.
  • Easy to use and learn.
  • Easily expandable.
  • Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
  • Easy to use for DOM manipulation and traversal.
  • Large pool of built in methods.
  • AJAX Capabilities.
  • Methods for changing or applying CSS, creating animations.
  • Event detection and handling.
  • Tons of plug-ins for all kind of needs.

Q3. How JavaScript and jQuery are different?

Ans: JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.

Q4. Is jQuery replacement of Java Script?

Ans: No. jQuery is not a replacement of JavaScript. jQuery is a different library which is written on top of JavaScript. jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.

Q5. Is jQuery a library for client scripting or server scripting?

Ans. Client side scripting.

Q6. Is jQuery a W3C standard?

Ans: No. jQuery is not a W3C standard.

Q7. What is the basic need to start with jQuery?

Ans: To start with jQuery, one need to make reference of it's library. The latest version of jQuery can be downloaded from jQuery.com.

Q8. Which is the starting point of code execution in jQuery?

Ans: The starting point of jQuery code execution is $(document).ready() function which is executed when DOM is loaded.

Q9. What does dollar sign ($) means in jQuery?

Ans: Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code.
$(document).ready(function(){  });  
Over here $ sign can be replaced with "jQuery" keyword.
jQuery(document).ready(function(){  });  

Q10. Can we have multiple document.ready() function on the same page?

Ans: YES. We can have any number of document.ready() function on the same page.

Q11. Can we use our own specific character in the place of $ sign in jQuery?

Ans: Yes. It is possible using jQuery.noConflict().

Q12. Is it possible to use other client side libraries like MooTools, Prototype along with jQuery?

Ans: Yes.

Q13. What is jQuery.noConflict?

Ans: As other client side libraries like MooTools, Prototype can be used with jQuery and they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().
jQuery.noConflict();  // Use jQuery via jQuery(...)  jQuery(document).ready(function(){     jQuery("div").hide();  });  
You can also use your own specific character in the place of $ sign in jQuery.
var $j = jQuery.noConflict();  // Use jQuery via jQuery(...)  $j(document).ready(function(){     $j("div").hide();  });    

Q14. Is there any difference between body onload() and document.ready() function?

Ans: document.ready() function is different from body onload() function for 2 reasons.
  1. We can have more than one document.ready() function in a page where we can have only one body onloadfunction.
  2. document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

Q15. What is the difference between .js and .min.js?

Ans: jQuery library comes in 2 different versions Production and Deployment. The deployment version is also known as minified version. So .min.js is basically the minified version of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.

Q16. Why there are two different version of jQuery library?

Ans: jQuery library comes in 2 different versions.
  1. Production
  2. Deployment
The production version is quite useful at development time as jQuery is open source and if you want to change something then you can make those changes in production version. But the deployment version is minified version or compressed version so it is impossible to make changes in it. Because it is compressed, so its size is very less than the production version which affects the page load time.

Q17. What is a CDN?

Ans: A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance.

Q18. Which are the popular jQuery CDN? and what is the advantage of using CDN?

Ans: There are 3 popular jQuery CDNs.
  1. 1. Google.
  2. 2. Microsoft
  3. 3. jQuery.
Advantage of using CDN.
  • It reduces the load from your server.
  • It saves bandwidth. jQuery framework will load faster from these CDN.
  • The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN

Q19. How to load jQuery from CDN?

Ans: Below is the code to load jQuery from all 3 CDNs.
Code to load jQuery Framework from Google CDN
<script type="text/javascript"      src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">  </script>  
Code to load jQuery Framework from Microsoft CDN
<script type="text/javascript"      src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">  </script>  
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
<script type="text/javascript"      src="http://code.jquery.com/jquery-1.9.1.min.js">  </script>  

Q20. How to load jQuery locally when CDN fails?

Ans: It is a good approach to always use CDN but sometimes what if the CDN is down (rare possibility though) but you never know in this world as anything can happen.

Below given jQuery code checks whether jQuery is loaded from Google CDN or not, if not then it references the jQuery.js file from your folder.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  <script type="text/javascript">  if (typeof jQuery == 'undefined')  {    document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));  }  </script>
It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

Q21. What are selectors in jQuery and how many types of selectors are there?

Ans: To work with an element on the web page, first we need to find them. To find the html element in jQuery we use selectors. There are many types of selectors but basic selectors are:

  • Name: Selects all elements which match with the given element Name.
  • #ID: Selects a single element which matches with the given ID
  • .Class: Selects all elements which match with the given Class.
  • Universal (*): Selects all elements available in a DOM.
  • Multiple Elements E, F, G: Selects the combined results of all the specified selectors E, F or G.
  • Attribute Selector: Select elements based on its attribute value.

Q22. How do you select element by ID in jQuery?

Ans: To select element use ID selector. We need to prefix the id with "#" (hash symbol). For example, to select element with ID "txtName", then syntax would be,
$('#txtName')  

Q23. What does $("div") will select?

Ans: This will select all the div elements on page.

Q24. How to select element having a particular class (".selected")?

Ans: $('.selected'). This selector is known as class selector. We need to prefix the class name with "." (dot).

Q25. What does $("div.parent") will select?

Ans: All the div element with parent class.

Q26. What are the fastest selectors in jQuery?

Ans: ID and element selectors are the fastest selectors in jQuery.

Q27. What are the slow selectors in jQuery?

Ans: class selectors are the slow compare to ID and element.

Q28. How jQuery selectors are executed?

Ans: Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".
$("p#elmID .myCssClass");  

Q29. Which is fast document.getElementByID('txtName') or $('#txtName').?

Ans: Native JavaScipt is always fast. jQuery method to select txtName "$('#txtName')" will internally makes a call todocument.getElementByID('txtName'). As jQuery is written on top of JavaScript and it internally uses JavaScript only So JavaScript is always fast.

Q30. Difference between $(this) and 'this' in jQuery?

Ans: this and $(this) refers to the same element. The only difference is the way they are used. 'this' is used in traditional sense, when 'this' is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.
$(document).ready(function(){      $('#spnValue').mouseover(function(){         alert($(this).text());    });  });
In below example, this is an object but since it is not wrapped in $(), we can't use jQuery method and use the native JavaScript to get the value of span element.
$(document).ready(function(){      $('#spnValue').mouseover(function(){         alert(this.innerText);    });  });






Q31. How do you check if an element is empty?

Ans: There are 2 ways to check if element is empty or not. We can check using ":empty" selector.
$(document).ready(function(){      if ($('#element').is(':empty')){         //Element is empty    }  });  
And the second way is using the "$.trim()" method.
$(document).ready(function(){      if($.trim($('#element').html())=='') {         //Element is empty    }  });  

Q32. How do you check if an element exists or not in jQuery? 

Ans: Using jQuery length property, we can ensure whether element exists or not.
$(document).ready(function(){      if ($('#element').length > 0){         //Element exists    });  });

Q33. What is the use of jquery .each() function?

Ans: The $.each() function is used to iterate over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.

Q34. What is the difference between jquery.size() and jquery.length?

Ans: jQuery .size() method returns number of element in the object. But it is not preferred to use the size()method as jQuery provide .length property and which does the same thing. But the .length property is preferred because it does not have the overhead of a function call.

Q35. What is the difference between $('div') and $('<div/>') in jQuery?

Ans: $('<div/>') : This creates a new div element. However this is not added to DOM tree unless you don't append it to any DOM element.

$('div') : This selects all the div element present on the page.

Q36. What is the difference between parent() and parents() methods in jQuery?

Ans: The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.

Q37. What is the difference between eq() and get() methods in jQuery?

Ans: eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used. Find out more here.

Q38. How do you implement animation functionality?

Ans: The .animate() method allows us to create animation effects on any numeric CSS property. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Syntax is:
(selector).animate({styles},speed,easing,callback)
  • styles: Specifies one or more CSS properties/values to animate.
  • duration: Optional. Specifies the speed of the animation.
  • easing: Optional. Specifies the speed of the element in different points of the animation. Default value is "swing".
  • callback: Optional. A function to be executed after the animation completes.
Simple use of animate function is,
$("btnClick").click(function(){    $("#dvBox").animate({height:"100px"});  });  

Q39. How to disable jQuery animation?

Ans: Using jQuery property "jQuery.fx.off", which when set to true, disables all the jQuery animation. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

Q40. How do you stop the currently-running animation?

Ans: Using jQuery ".stop()" method.

Q41. What is the difference between .empty(), .remove() and .detach() methods in jQuery?

Ans: All these methods .empty(), .remove() and .detach() are used for removing elements from DOM but they all are different.

.empty(): This method removes all the child element of the matched element where remove() method removes set of matched elements from DOM.

.remove(): Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

.detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

Find out more here

Q42. Explain .bind() vs .live() vs .delegate() vs .on()

Ans: All these 4 jQuery methods are used for attaching events to selectors or elements. But they all are different from each other.

.bind(): This is the easiest and quick method to bind events. But the issue with bind() is that it doesn't work for elements added dynamically that matches the same selector. bind() only attach events to the current elements not future element. Above that it also has performance issues when dealing with a large selection.

.live(): This method overcomes the disadvantage of bind(). It works for dynamically added elements or future elements. Because of its poor performance on large pages, this method is deprecated as of jQuery 1.7 and you should stop using it. Chaining is not properly supported using this method.

.delegate(): The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored and it also supports chaining.

.on(): Since live was deprecated with 1.7, so new method was introduced named ".on()". This method provides all the goodness of previous 3 methods and it brings uniformity for attaching event handlers.

Find out more here

Q43. What is wrong with this code line "$('#myid.3').text('blah blah!!!');"

Ans: The problem with above statement is that the selectors is having meta characters and to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").
So the correct syntax is,
$('#myid\\.3').text('blah blah!!!');  

Q44. How to create clone of any object using jQuery?

Ans: jQuery provides clone() method which performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.
$(document).ready(function(){    $('#btnClone').click(function(){       $('#dvText').clone().appendTo('body');       return false;    });  });  

Q45. Does events are also copied when you clone any element in jQuery?

Ans: As explained in previous question, using clone() method, we can create clone of any element but the default implementation of the clone() method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.
$(document).ready(function(){     $("#btnClone").bind('click', function(){       $('#dvClickme').clone(true).appendTo('body');    });  
​ 

Q46. What is difference between prop and attr?

Ans: attr(): Get the value of an attribute for the first element in the set of matched elements. Whereas,.prop(): (Introduced in jQuery 1.6) Get the value of a property for the first element in the set of matched elements.

Attributes carry additional information about an HTML element and come in name="value" pairs. Where Property is a representation of an attribute in the HTML DOM tree. once the browser parse your HTML code ,corresponding DOM node will be created which is an object thus having properties.

attr() gives you the value of element as it was defines in the html on page load. It is always recommended to useprop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element's current state. Find out more here.

Q47. What is event.PreventDefault?

Ans: The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.

Q48. What is the difference between event.PreventDefault and event.stopPropagation?

Ans: event.preventDefault(): Stops the default action of an element from happening.
event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

Q49. What is the difference between event.PreventDefault and "return false"?

Ans: e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.

Q50. What is the difference between event.stopPropagation and event.stopImmediatePropagation?

Ans: event.stopPropagation() allows other handlers on the same element to be executed, whileevent.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.
$("p").click(function(event){    event.stopImmediatePropagation();  });  $("p").click(function(event){    // This function won't be executed    $(this).css("background-color", "#f00");  });   
If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire. 

Q51. How to check if number is numeric while using jQuery 1.7+?

Ans: Using "isNumeric()" function which was introduced with jQuery 1.7.

Q52. How to check data type of any variable in jQuery?

Ans: Using $.type(Object) which returns the built-in JavaScript type for the object.

Q53. How do you attach a event to element which should be executed only once?

Ans: Using jQuery one() method. This attaches a handler to an event for the element. The handler is executed at most once per element. In simple terms, the attached function will be called only once.
$(document).ready(function() {      $("#btnDummy").one("click", function() {          alert("This will be displayed only once.");      });  });​  

Q54. Can you include multiple version of jQuery? If yes, then how they are executed?

Ans: Yes. Multiple versions of jQuery can be included in same page.

Q55. In what situation you would use multiple version of jQuery and how would you include them?

Ans: Well, it is quite possible that the jQuery plugins which are used are dependent on older version but for your own jQuery code, you would like to use newer version. So because of this dependency, multiple version of jQuery may required sometimes on single page.

Below code shows how to include multiple version of jQuery.
<script type='text/javascript' src='js/jquery_1.9.1.min.js'></script>    <script type='text/javascript'>   var $jq = jQuery.noConflict();  </script>    <script type='text/javascript' src='js/jquery_1.7.2.min.js'></script>  
By this way, for your own jQuery code use "$jq", instead of "$" as "$jq" refers to jQuery 1.9.1, where "$" refers to 1.7.2.

Q56. Is it possible to hold or delay document.ready execution for sometime?

Ans: Yes, its possible. With Release of jQuery 1.6, a new method "jQuery.holdReady(hold)" was introduced. This method allows to delay the execution of document.ready() event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced.
​  $.holdReady(true);  $.getScript("myplugin.js", function() {       $.holdReady(false);  });  

Q57. What is chaining in jQuery?

Ans: Chaining is one of the most powerful feature of jQuery. In jQuery, Chaining means to connect multiple functions, events on selectors. It makes your code short and easy to manage and it gives better performance. The chain starts from left to right. So left most will be called first and so on.
​$(document).ready(function(){      $('#dvContent').addClass('dummy');      $('#dvContent').css('color', 'red');      $('#dvContent').fadeIn('slow');  });​
The above jQuery code sample can be re-written using chaining. See below.
​$(document).ready(function(){      $('#dvContent').addClass('dummy')            .css('color', 'red')            .fadeIn('slow');       });​
Not only functions or methods, chaining also works with events in jQuery. Find out more here.

Q58. How does caching helps and how to use caching in jQuery? 

Ans: Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.
$("#myID").css("color", "red");  //Doing some other stuff......  $("#myID").text("Error occurred!");  ​
Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,
var $myElement = $("#myID").css("color", "red");  //Doing some other stuff......  $myElement.text("Error occurred!");  ​
So now in this case, jQuery won't need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

Q59. You get "jquery is not defined" or "$ is not defined" error. What could be the reason?

Ans: There could be many reasons for this.
  • You have forgot to include the reference of jQuery library and trying to access jQuery.
  • You have include the reference of the jQuery file, but it is after your jQuery code.
  • The order of the scripts is not correct. For example, if you are using any jQuery plugin and you have placed the reference of the plugin js before the jQuery library then you will face this error.
Find out more here.

Q60. How to write browser specific code using jQuery?

Ans: Using jQuery.browser property, we can write browser specific code. This property contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9. 

Q61. Can we use jQuery to make ajax request?

Ans: Yes. jQuery can be used for making ajax request.

Q62. What are various methods to make ajax request in jQuery?

Ans: Using below jQuery methods, you can make ajax calls.
  • load() : Load a piece of html into a container DOM
  • $.getJSON(): Load JSON with GET method.
  • $.getScript(): Load a JavaScript file.
  • $.get(): Use to make a GET call and play extensively with the response.
  • $.post(): Use to make a POST call and don't want to load the response to some container DOM.
  • $.ajax(): Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.
Find out more here.

Q63. Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()?

Ans: By using jQuery post()/ jQuery get(), you always trust the response from the server and you believe it is going to be successful all the time. Well, it is certainly not a good idea to trust the response. As there can be n number of reason which may lead to failure of response.

Where jQuery.ajax() is jQuery's low-level AJAX implementation. $.get and $.post are higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks). Find out more here.

Q64. What are deferred and promise object in jQuery?

Ans: Deferred and promise are part of jQuery since version 1.5 and they help in handling asynchronous functions like Ajax. Find out more here.

Q65. Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how?

Ans: Yes, it is possible to execute multiple Ajax request simultaneously or in parallel. Instead of waiting for first ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple ajax request simultaneously.

Using jQuery .when() method which provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. Find out more here.

Q66. Can you call C# code-behind method using jQuery? If yes,then how?

Ans: Yes. We can call C# code-behind function via $.ajax. But for do that it is compulsory to mark the method as WebMethod.

Q67. Which is the latest version of jQuery library?

Ans: The latest version (when this post is written) of jQuery is 1.10.2 or 2.0.3. jQuery 2.x has the same API as jQuery 1.x, but does not support Internet Explorer 6, 7, or 8.

Q68. Does jQuery 2.0 supports IE?

Ans: No. jQuery 2.0 has no support for IE 6, IE 7 and IE 8.

Q69. What are source maps in jQuery?

Ans: In case of jQuery, Source Map is nothing but mapping of minified version of jQuery against the un-minified version. Source map allows to debug minified version of jQuery library. Source map feature was release with jQuery 1.9. Find out more here.

Q70. How to use migrate jQuery plugin?

Ans: with release of 1.9 version of jQuery, many deprecated methods were discarded and they are no longer available. But there are many sites in production which are still using these deprecated features and it's not possible to replace them overnight. So jQuery team provided with jQuery Migrate plugin that makes code written prior to 1.9 work with it.

So to use old/deprecated features, all you need to do is to provide reference of jQuery Migrate Plugin. Find out morehere

Q71. Is it possible to get value of multiple CSS properties in single statement?

Ans: Well, before jQuery 1.9 release it was not possible but one of the new feature of jQuery 1.9 was .css() multi-property getter.
var propCollection = $("#dvBox").css([ "width", "height", "backgroundColor" ]);  
In this case, the propCollection will be an array and it will look something like this.
{     width: "100px",     height: "200px",     backgroundColor: "#FF00FF"   }  

Q72. How do you stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements?

Ans: It can be done via calling .stop([clearQueue ] [, jumpToEnd ]) method and by passing both the parameters as true.

Q73. What is finish method in jQuery?

Ans: The .finish() method stops all queued animations and places the element(s) in their final state. This method was introduced in jQuery 1.9.

Q74. What is the difference between calling stop(true,true) and finish method?

Ans: The .finish() method is similar to .stop(true, true) in that it clears the queue and the current animation jumps to its end value. It differs, however, in that .finish() also causes the CSS property of all queued animations to jump to their end values, as well.

Q75. Consider a scenario where things can be done easily with javascript, would you still prefer jQuery?

Ans: No. If things can be done easily via CSS or JavaScript then You should not think about jQuery. Remember, jQuery library always comes with xx kilobyte size and there is no point of wasting bandwidth.

Q76. Can we use protocol less URL while referencing jQuery from CDNs?

Ans: Yes. Below code is completely valid.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  

Q77. What is the advantage of using protocol less URL while referencing jQuery from CDNs?

Ans: It is quite useful when you are moving from HTTP to HTTPS url. You need to make sure that correct protocol is used for referencing jQuery library as pages served via SSL should contain no references to content served through unencrypted connections.

"protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead. Find out more here.

Q78. What is jQuery plugin and what is the advantage of using plugin?

Ans: A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery methods which can be used along with jQuery library methods. jQuery plugins are quite useful as its piece of code which is already written by someone and re-usable, which saves your development time.

Q79. What is jQuery UI?

Ans: jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library that can be used to build interactive web applications.

Q80. What is the difference between jQuery and jQuery UI?

Ans: jQuery is the core library. jQueryUI is built on top of it. If you use jQueryUI, you must also include jQuery.