Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday, February 16, 2010

How to clear asp.net fileupload control using javascript?

Note: The below code will works in both IE and Firefox.

function Clear(elem)
{
var who =document.getElementById(elem.id);
who.value="";
var who2= who.cloneNode(false);
who2.onchange= who.onchange;
who.parentNode.replaceChild(who2,who);
document.getElementById(elem.id).select();
}

Filter files in fileupload control open dialog by file extensions using javascript?

Note: As like windows .Net its not possible to show only specific file extensions,the only way is that we can validate it by manually as shown below.

function checkFileExtension(elem)
{
var filePath = elem.value;

if(filePath.indexOf('.') == -1)
return false;

var validExtensions = new Array();
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();

validExtensions[0] = 'pdf';
//validExtensions[1] = 'jpg';
//validExtensions[2] = 'txt';

for(var i = 0; i < validExtensions.length; i++)
{
if(ext == validExtensions[i])
{

return true;
}
}

alert('The file extension ' + ext.toUpperCase() + ' is not allowed,select PDF.');

return false;
}


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

FileUpload1.Attributes.Add("onchange", "return checkFileExtension(this);");

Monday, August 10, 2009

Tuesday, July 7, 2009

How to disable ctrl key combinations using Javascript?

function disableCtrlKeyCombination(e)
{
//list all CTRL + key combinations you want to disable
var forbiddenkeys = new Array('a','n','c','x','v','j');
var key;
var isCtrl;

if(window.event)
{
key = window.event.keyCode; //IE
if(window.event.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}
else
{
key = e.which; //firefox
if(e.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}

//if ctrl is pressed check if other key is in forbidenKeys array
if(isCtrl)
{
for(i=0; i < forbiddenkeys.length; i++)
{
//case-insensitive comparation
if(forbiddenkeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase())
{
alert('Key combination CTRL'+ String.fromCharCode(key) + ' has been disabled.');
return false;
}
}
}
return true;
}

//=====================
< body onkeydown="return disableCtrlKeyCombination(event);"> < /body>

Friday, December 26, 2008

How to detect Capslock is On/Off using Javascript?

<asp:TextBox ID="TextBox1" onkeypress="capsDetect(arguments[0]);" runat="server"></asp:TextBox>

<script language="javascript" type="text/javascript">
var capsError = 'WARNING:\n\nCaps Lock is enabled\n\nThis field is case sensitive';

function capsDetect( e ) {
if( !e ) { e = window.event; } if( !e ) { MWJ_say_Caps( false ); return; }
//what (case sensitive in good browsers) key was pressed
var theKey = e.which ? e.which : ( e.keyCode ? e.keyCode : ( e.charCode ? e.charCode : 0 ) );
//was the shift key was pressed
var theShift = e.shiftKey || ( e.modifiers && ( e.modifiers & 4 ) ); //bitWise AND
//if upper case, check if shift is not pressed. if lower case, check if shift is pressed
MWJ_say_Caps( ( theKey > 64 && theKey < 91 && !theShift ) || ( theKey > 96 && theKey < 123 && theShift ) );
}
function MWJ_say_Caps( oC ) {
if( typeof( capsError ) == 'string' ) { if( oC ) { alert( capsError ); } } else { capsError( oC ); }
}
</script>

Tuesday, November 18, 2008

How to convert numbers to words using javascript?

// American Numbering System
var th = ['','thousand','million', 'billion','trillion'];
// uncomment this line for English Number System
// var th = ['','thousand','million', 'milliard','billion'];

var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
function toWords(s)
{
s = document.getElementById(s.id).value; //Source Control
//s = s.toString();
s = s.replace(/[\, ]/g,'');
if (s != String(parseFloat(s)))
return 'not a number';
var x = s.indexOf('.');
if (x == -1) x = s.length;
if (x > 15)
return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i=0; i < x; i++)
{
if ((x-i)%3==2)
{
if (n[i] == '1')
{
str += tn[Number(n[i+1])] + ' ';
i++; sk=1;
}
else if (n[i]!=0)
{
str += tw[n[i]-2] + ' ';
sk=1;
}
}
else if (n[i]!=0)
{
str += dg[n[i]] +' ';
if ((x-i)%3==0)
str += 'hundred ';
sk=1;
}
if ((x-i)%3==1)
{
if (sk)
str += th[(x-i-1)/3] + ' ';
sk=0;
}
}
if (x != s.length)
{
var y = s.length;
str += 'point ';
for (var i=x+1; i str += dg[n[i]] +' ';
}
document.getElementById('TxtWords').value=str.replace(/\s+/g,' ') +' ' + 'rupees only'; //TargetControl
//return str.replace(/\s+/g,' ');
}

How to remove white space,special characters and return only numbers using javascript

function RemoveSpecialChar()
{
var A;
var B;
A=document.getElementById('TextBox1').value;
B= filterNum(A);
document.getElementById('TextBox2').value=noAlpha(whitespace(B));
function filterNum(str)
{
re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
return str.replace(re, "");
}
function whitespace(str)
{
str = str.replace(/\s+/g,'');
return str;
// \s+ Description
// + 1 or more of previous expression.
// \s Matches any white-space character.
// Equivalent to the Unicode character categories [\f\n\r\t\v\x85\p{Z}].
// If ECMAScript-compliant behavior is specified with the ECMAScript option,
// \s is equivalent to [ \f\n\r\t\v].
}
function noAlpha(obj)
{
reg = /[^0-9.,]/g;
return obj.replace(reg,"");
}
}

How To Find Date Difference Using Javascript?

function Date_Diff()
{
var dt1=document.getElementById('TextBox1').value;//Start Date
var dt2=document.getElementById('TextBox2').value;//End Date
dt1=dt1.split('/');
dt2=dt2.split('/');
var st=new Date(dt1[2],dt1[0],dt1[1]);
var ed=new Date(dt2[2],dt2[0],dt2[1]);
if (ed > st)
alert('True');
else
alert('False');
}

Thursday, September 4, 2008

How to remove alphabets,special characters and white space in a string and return only numbers using javascript?

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

function RemoveSpecialChar()
{
var A;
var B;
A=document.getElementById('TextBox1').value;
B= filterNum(A);
document.getElementById('TextBox2').value=noAlpha(whitespace(B));
function filterNum(str)
{
re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
return str.replace(re, "");
}
function whitespace(str)
{
str = str.replace(/\s+/g,'');
return str;
// \s+ Description
// + 1 or more of previous expression.
// \s Matches any white-space character.
// Equivalent to the Unicode character categories [\f\n\r\t\v\x85\p{Z}].
// If ECMAScript-compliant behavior is specified with the ECMAScript option,
// \s is equivalent to [ \f\n\r\t\v].
}
function noAlpha(obj)
{
reg = /[^0-9.,]/g;
return obj.replace(reg,"");
}
}
</script>

How to find the date is greater than or not using javascript?

function Date_Diff()
{
var dt1=document.getElementById('TextBox1').value;//Start Date
var dt2=document.getElementById('TextBox2').value;//End Date
dt1=dt1.split('/');
dt2=dt2.split('/');
var st=new Date(dt1[2],dt1[0],dt1[1]);
var ed=new Date(dt2[2],dt2[0],dt2[1]);
if (ed > st)
alert('True');
else
alert('False');
}

How set control id through javascript?

<script type="text/javascript">
function setTableID()
{
document.getElementsByTagName("table")[0].setAttribute("id","tableid");
}
onload =setTableID;
</script>

How set control id through javascript?

<script type="text/javascript">
function setTableID()
{
document.getElementsByTagName("table")[0].setAttribute("id","tableid");
}
onload =setTableID;
</script>

How to freeze ASP.NET Gridview header?

<style type="text/css">
.WrapperDiv {
width:800px;height:400px;border: 1px solid black;
}
.WrapperDiv TH {
position:relative;
}
.WrapperDiv TR
{
/* Needed for IE */
height:0px;
}
</style>
<script>
function onLoad()
{
FreezeGridViewHeader('GridView1','WrapperDiv');
}


function FreezeGridViewHeader(gridID,wrapperDivCssClass)
{
/// <summary>
/// Used to create a fixed GridView header and allow scrolling
/// </summary>
/// <param name="gridID" type="String">
/// Client-side ID of the GridView control
/// </param>
/// <param name="wrapperDivCssClass" type="String">
/// CSS class to be applied to the GridView's wrapper div element.
/// Class MUST specify the CSS height and width properties.
/// Example: width:800px;height:400px;border:1px solid black;
/// </param>
var grid = document.getElementById(gridID);
if (grid != 'undefined')
{
grid.style.visibility = 'hidden';
var div = null;
if (grid.parentNode != 'undefined')
{
//Find wrapper div output by GridView
div = grid.parentNode;
if (div.tagName == "DIV")
{
div.className = wrapperDivCssClass;
div.style.overflow = "auto";
}
}
//Find DOM TBODY element and remove first TR tag from
//it and add to a THEAD element instead so CSS styles
//can be applied properly in both IE and FireFox
var tags = grid.getElementsByTagName('TBODY');
if (tags != 'undefined')
{
var tbody = tags[0];
var trs = tbody.getElementsByTagName('TR');
var headerHeight = 8;
if (trs != 'undefined')
{
headerHeight += trs[0].offsetHeight;
var headTR = tbody.removeChild(trs[0]);
var head = document.createElement('THEAD');
head.appendChild(headTR);
grid.insertBefore(head, grid.firstChild);
}
//Needed for Firefox
tbody.style.height =
(div.offsetHeight - headerHeight) + 'px';
tbody.style.overflowX = "hidden";
tbody.overflow = 'auto';
tbody.overflowX = 'hidden';
}
grid.style.visibility = 'visible';
}
}
</script>

===============
Protected Sub BtnView_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnView.Click
GVReport.DataSource = dtreport 'Datatable
GVReport.DataBind()
ScriptManager.RegisterStartupScript(Me, Me.GetType, "", "GridHeader('GVReport');", True)
End Sub

How to get the Dropdownlist selected item text using javascript?

function Enable(obj,ctrl)
{
var DDL = document.all(obj.id);
var curText = DDL.options[DDL.selectedIndex].text;
if(curText=='--Select--')
document.getElementById(ctrl).disabled=true;
else
document.getElementById(ctrl).disabled=false;

}

Wednesday, March 5, 2008

What are all the Mathematical functions supported by Javascript

JavaScript supports the following mathematical functions (methods of the Math object)

Math.abs(a) // the absolute value of a
Math.acos(a) // arc cosine of a
Math.asin(a) // arc sine of a
Math.atan(a) // arc tangent of a
Math.atan2(a,b) // arc tangent of a/b
Math.ceil(a) // integer closest to a and not less than a
Math.cos(a) // cosine of a
Math.exp(a) // exponent of a
Math.floor(a) // integer closest to and not greater than a
Math.log(a) // log of a base e
Math.max(a,b) // the maximum of a and b
Math.min(a,b) // the minimum of a and b
Math.pow(a,b) // a to the power b
Math.random() // pseudorandom number in the range 0 to 1
Math.round(a) // integer closest to a
Math.sin(a) // sine of a
Math.sqrt(a) // square root of a
Math.tan(a) // tangent of a

Note that trigonometric functions assume that the argument is in radians,not degrees!

Tuesday, March 4, 2008

How to find the version of the IE Browser using Javascript

var version = navigator.appVersion;
function Version() // onload
{
if (version.indexOf('MSIE 7.0') != -1)
alert("U R Using IE 7");
else
alert("Some Other");
}

How to Block Special Characters in a Textbox using Javascript

<asp:TextBox id="Txt" onkeydown="return BlockShift();" runat="server"/>
function BlockShift()
{
if(event.shiftKey)
return false;
}

How to set focus at the end of the Text in a Textbox using Javascript

//Setting Focus At the end of the Text in a TextBox
function SetEnd (obj)
{
var ctrl=document.getElementById(obj.id);
if (ctrl.createTextRange)
{
var FieldRange = ctrl.createTextRange();
FieldRange.moveStart('character', ctrl.value.length);
FieldRange.collapse();
FieldRange.select();
}
}

How to validate the email address using javascript

var efmt=/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;

function EmailFormat(obj)
{
var ctrl=document.getElementById(obj.id);
if((!efmt.test(ctrl.value)) && ctrl.value!='')
{
alert('Please enter a valid email address, like xyz@example.com');
ctrl.value = "";
ctrl.focus();
}
}

Sunday, February 3, 2008

How to Get Session Values Through Javascript Code..

<head runat="server">
<script language="javascript">

function ChkPwd()
{
var pwd='<%= Session["ChgPwd"] %>';
alert(pwd);
}

</script>
<head>
 
Feedback Form