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
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;
}
// 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;
}