Archive for the ‘Javascript’ Category
Protected: ASP.NET Handling Browser’s Close Event And Perform Session Abandon
Posted: July 12, 2011 in ASP.NET, JavascriptTags: Browser Close Event, Detecting Broswer's Close Event, Handling Browser's Close Event, How to handle Browser's Close Event?, Session Abandon on Browser Close, Session Expire on Browser Close, Session Expire on Window Close
How to disable Anchor tag in IE and Firefox?
Posted: September 16, 2009 in ASP.NET, JavascriptTags: disable a tag, disable anchor, disable anchor tag
I have searched many sites for to disable anchor and I know that IE supports ‘disable’ property for anchor tag, however Firefox does not support this. So whenever you try with ‘disable’ property of an anchor tag “<a></a>” you will get proper output in IE browser but not in Firefox browsers.
I have found a very good article which disables the anchor tag using few tricks because without tricks it is not possible to mange disable anchor in Firefox. You can find this article here. However, you can copy the same javascript script of above article as below.
function disableAnchor(obj, disable){
if(disable){
var href = obj.getAttribute("href");
if(href && href != "" && href != null){
obj.setAttribute('href_bak', href);
}
obj.removeAttribute('href');
obj.style.color="gray";
}
else{
obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);
obj.style.color="blue";
}
}
Also note that you can perform the same thing on the code behind (for asp.net) if you are using a server control for anchor tag and you want to disable the anchor, you just need to remove the ‘href’ property using MyAnchor.Attributes.Remove("href") and then just apply gray color to anchor and its done. It will work in both IE and Firefox (javascript and server code both).
Happy Programming!!
Auto refresh the page and keep the viewstate of the page on each refresh
Posted: August 21, 2009 in ASP.NET, JavascriptTags: auto refresh page, auto refresh page and keep viewstate, auto-refresh page and persist viewstate of the page, keep viewstate on every refresh, keep viewstate
Today I am writing about how you can auto-refresh the page and still how you can manage the view-state of the page.
There may be requirement to fill up a long lasting form and this might take you a longer time to think or type. Now the general problem that occurs while filling up this kind of form is when you submit the form the session got expired or the timeout event occurs. So to overcome this situation we can set some timer to that particular page for refresh so that after several minutes it got refreshed automatically and we did not face any timeout or session related issues.
Now there are several ways to auto-refresh the page, the one is to put meta tag like <meta http-equiv="refresh" content="600">. What this tag will do is it will refresh the page after every 10 minutes, but when the page gets refresh then it will not persist the view-state of the page. This means if you are filling up any form and the page gets refreshed then you will not able to get all the filled content and the page will get loaded in its original form.
There was one requirement where I need to auto refresh the page as well as need to keep the view-state of the page. To achieve this I have put a simple JavaScript code on BODY tag of my page as below:
<Body onload="setTimeout('Form1.submit();', 600000);">
<form id="Form1" method="post" runat="server">
Here this JavaScript method “setTimeout()” will submit your form data after every 10 minutes and the page will also get refreshed so that it will also persist the view-state of the page after auto refresh of the page. Please note that the time 600000 here is in milliseconds. (1 second = 1000 milliseconds)
Happy Programming!
javascript: Word Counter
Posted: December 19, 2008 in ASP.NET, JavascriptTags: counter, Javascript, javascript textbox character counter, javascript word counter, word
Few months back I have posted one article on “Javascript: Maximum character validation and character counter for a textbox”, now here I have given one example on how to count words out of any textarea or textbox.
The counter of word will get incremented as you type in each word (one spell) into the textbox/textarea. This script will also work when anyone copy/paste the text into the textbox (copy/paste should not through mouse). Check the following script:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" TextMode="multiLine" MaxLength="100"
runat="server" onkeyup="javascript:WordCounter(this.id,'Label1');"
onblur="javascript:WordCounter(this.id,'Label1');"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="100 chars
remaining"></asp:Label>
</div>
<script language="javascript" type="text/javascript">
function WordCounter(textId,lblID)
{
var this_field = document.getElementById(textId);
var label = document.getElementById(lblID);
var char_count = this_field.value.length;
var fullStr = this_field.value + " ";
var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
var splitString = cleanedStr.split(" ");
var word_count = splitString.length -1;
if (fullStr.length <2)
{
word_count = 0;
}
if (word_count == 1)
{
wordOrWords = " word";
}
else
{
wordOrWords = " words";
}
if (char_count == 1)
{
charOrChars = " character";
}
else
{
charOrChars = " characters";
}
label.innerHTML = word_count + wordOrWords;
}
</script>
</form>
</body>
Happy Coding!!
Enable or disable DIV tag and its inner controls using Javascript
Posted: September 3, 2008 in JavascriptTags: javascript alternate "disable" Firefox, javascript disable DIV Firefox, javascript element disable Firefox, javascript enabled/disabled elements
Today, I was searching for a solution to enable/disable DIV element using javascript. I have tried so many code, but all are working in IE only and not supported by FF (firefox). At last I found some solution which is helpful. I thought this might also useful to you.
Copy/Paste following javascript code snippet.
<script type="text/javascript">
function toggleAlert() {
toggleDisabled(document.getElementById("content"));
}
function toggleDisabled(el) {
try {
el.disabled = el.disabled ? false : true;
}
catch(E){
}
if (el.childNodes && el.childNodes.length > 0) {
for (var x = 0; x < el.childNodes.length; x++) {
toggleDisabled(el.childNodes[x]);
}
}
}
</script>
Copy/Paste following HTML code in BODY tag:
<div id="content">
<table>
<tr>
<td><input type="text" name="foo" /></td>
</tr>
<tr>
<td>
<select name="bar">
<option>a</option>
<option>b</option>
<option>c</option>
</select>
</td>
</tr>
</table>
</div>
<input type="checkbox" value="toggleAlert()" onclick="toggleAlert()" />
Here, I have used one checkbox, by clicking which you can enable/disable child controls of a DIV. However, you can use any element other than checkbox (e.g button, radio button, etc…)
Javascript: innerText not working in FireFox and Safari
Posted: September 1, 2008 in JavascriptTags: alternate to innerText in javascript, javascript innerText not supported
Today, I came to know that innerText property of any web control is not supported by FireFox and Safari browser. Here, I found the alternate solution for innerText property.
Use the following code in javascript to acquire the same functionality as innerText.
var myText = document.getElementById(’divText’).textContent; // same as innertext.
Use Javascript to detect enterkey press event and submit the form
Posted: September 1, 2008 in ASP.NET, JavascriptTags: detect enterkey in a textbox and submit the form, javascript detect enterkey event
This code is useful in almost all kind of forms that has a submit button. When any user press “Enter key” also called a Return key in a textbox, this code will detect if the Enter key is pressed or not and will perform the same action as directed in a code of Submit button. Type the following javascript code befor a “body” tag.
function DetectEnterPressed(e) {
var characterCode
if(e && e.which){ // NN4 specific code
e = e
characterCode = e.which
}
else {
e = event
characterCode = e.keyCode // IE specific code
}
if (characterCode == 13) return true // Enter key is 13
else return false
}
Type the following line of code in a code behind file. You can put this code in a page_load method and outside the IsPostBack event.
txtPassword.Attributes.Add("onkeypress","javascript:return DetectEnterPressed(event);");
Get CheckBoxList values using Javascript
Posted: August 14, 2008 in ASP.NET, JavascriptTags: CheckBoxList and Javascript, Get CheckBoxList values, Get checked checkboxes from checkboxlist
Today I have spend lot of time to get the values of each item of CheckBoxList using javascript. And finally I got success.
What I want to do is:
I have one CheckBoxList control that binds values at runtime from the database, and when I click on a button from the page, I want to get the values (Database Primary Key) from the CheckBoxList, but for the checked checkboxes only.
Here is the code, what I have achieved so far. This code works fine with IE 7, but I am not sure with the FireFox.
ASPX page: <asp:CheckBoxList ID="CheckBoxList1" runat="server" OnDataBound="CheckBoxList1_DataBound" >
<asp:ListItem Value="First1" Text="First" ></asp:ListItem>
<asp:ListItem Value="second2" Text="Second"></asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="Button" />
<script language="javascript" type="text/javascript">
function CheckItem()
{
var tbl = document.getElementById('<%= CheckBoxList1.ClientID %>').childNodes[0];
for(var i=0; i<tbl.childNodes.length;i++)
{
for(var k=0; k<tbl.childNodes[i].childNodes.length; k++)
{
if(tbl.childNodes[i].childNodes[k].nodeName == "TD")
{
var currentTD = tbl.childNodes[i].childNodes[k];
for(var j=0; j<currentTD.childNodes.length; j++)
{
if(currentTD.childNodes[j].nodeName == "SPAN")
{
var currentSpan = currentTD.childNodes[j];
for(var l=0; l<currentSpan.childNodes.length; l++)
{
if(currentSpan.childNodes[l].nodeName == "INPUT" && currentSpan.childNodes[l].type == "checkbox")
{
var currentChkBox = currentSpan.childNodes[l];
if(currentChkBox.checked)
{
alert(currentSpan.alt);
}
}
}
}
}
}
}
}
}
</script>
Code Behind:
Button1.Attributes.Add("onclick", "javascript:CheckItem();");
CheckBoxList1.DataSource = <Your Dataset>;
CheckBoxList1.DataTextField = "PersonName";
CheckBoxList1.DataValueField = "PersonID";
CheckBoxList1.DataBind();
protected void CheckBoxList1_DataBound(object sender, EventArgs e)
{
CheckBoxList chkList = (CheckBoxList)(sender);
foreach (ListItem item in chkList.Items)
{
item.Attributes.Add("alt", item.Value);
}
}
Javascript: Maximum character validation and character counter for a textbox
Posted: August 14, 2008 in ASP.NET, JavascriptTags: javascript check maximum character length validation, javascript textbox character counter, textbox character counter
Here I have provided a solution to put a counter for a textbox, that can be updated as each character typed into the textbox. This script will also validate the maximum character length allowed for a textbox. This script will also work when anyone copy/paste the text into the textbox. Textbox can be either single line or multi line. Check the following script:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" TextMode="multiLine" MaxLength="100" runat="server" onkeyup="javascript:CharCounter(this.id);" onblur="javascript:CharCounter(this.id);"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="100 chars remaining"></asp:Label>
</div>
<script language="javascript" type="text/javascript">
function CharCounter(textId)
{
var totalchar = '<%= TextBox1.MaxLength %>';
var txtbox = document.getElementById(textId);
var lbl = document.getElementById('<% =Label1.ClientID %>');
if(txtbox.value.length > totalchar)
{
txtbox.value = txtbox.value.substring(0,totalchar);
}
lbl.innerText = (totalchar - txtbox.value.length) + " chars remaining" ;
}
</script>
</form>
</body>
Happy Coding!!