Quick JavaScript Confirm Message Validator

For a quick and simple confirm message validator fire an OnClientClick event on the element required to validate. For instance on a delete link paste the following javascript call:

OnClientClick=”javascript:return confirm(‘Are you sure you want to Delete?’);”

This will display a pop up message giving yes or no as an option. If no is clicked, the click event is ignored, if yes is clicked, the click event is accepted.

Create a textbox watermark using CSS and jQuery

Step 1: –

First of all, we need to reference the latest jquery plugin (at the time being  version 1.9.1):

<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js“></script>

Step 2:-

Add some styling to the textbox watermark, which is usually a light grey text font

<style>

.watermark
{

font-family: Calibri, Arial;

font-size: 14px;

color:gray;

}

</style>

Continue reading

Using Google API Heat Maps

Google HeatMaps

P.S full code at bottom of page

Step 1 :- Add Reference to Google JavaScript API

<script src=”https://maps.googleapis.com/maps/api/js?sensor=false&libraries=visualization ” type=”text/javascript”></script>

Parameters Explained:

1. Sensor (Obligatory)

Sensor can be either set to true or false to inform the API if the maps are being accessed from a device with location such as a smart phone or not such as a desktop.

If the sensor parameter is not passed, the API will return a “Request Denied” error.

2. libraries(optional)

When references Google API, we are still not loading everything. Therefore, we can load these libraries using parameters in the URL. The Visualization library is required when we want to visualize some sort of data using markers, heat maps, or circle size maps.

Continue reading

Error during serialization or deserialization using the JSON JavaScriptSerializer

Scope: 

Returning a DataTable from a WebMethod to JavaScript using C#

WebMethod in code behind:

[WebMethod(BufferResponse = false, CacheDuration = 5)]
public static string GetUsers()
{

//Using Subsonic //Replace with your queries to return a dataset
System.Data.DataSet users= DB.Select().From(Tables.Users).ExecuteDataSet();

return users.GetXml();

}

JavaScript:

function getUsersUpdate() {
$.ajax({
type: “POST”,
url: “default.aspx/GetUsers”,
data: ‘{}’,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: OnCompleteSuccess,
failure: OnCompleteFailure,
error: OnCompleteError
});
return false;
}

function OnCompleteSuccess(response)
{
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
alert(xml);
}

function OnCompleteFailure(response) {
alert(“Failed: ” + response.reponseText);
}
function OnCompleteError(response) {
alert(“Error Occurred: ” + response.responseText);   //This is where the JSON serialization error is caught
}

Reason for error:

Your DataSet if returning large amount of JSON data while the web.config is configured to allow a max amount of JSON serialization data.

Solution to error:

Remove the max amount of data allowed in the web.config to cater for large amount of JSON data.

In the Web.Config:

Under the <system.web> </system.web> copy and paste the following configs:

<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength=”99999999″/>
</webServices>
</scripting>
</system.web.extensions>

P.S: Make sure that under the <configsection> within the <sectiongroup> you have one section similar to the below:

<section name=”jsonSerialization” type=”System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ requirePermission=”false” allowDefinition=”Everywhere”/>

if not, add that too.

Javascript Write Properties

To Write in a TextBox / input / label:

document.getElementById(“sample”).value = “Hello”;

 

To Write in a divider / paragraph / span :

document.getElementById(“sample”).innerText = “Hello”;

 

To Write in a divider / paragraph / span     using FireFox :

document.getElementById(“sample”).textContent = “Hello”;

 

To Look for a word in a TextBox / input / label (if it does not find it, it returns null):

document.getElementById(“sample”).value.match(“Hello”);

 

To Look for a word in a divider / paragraph / span (if it does not find it, it returns null):

document.getElementById(“sample”).innerText.match(“Hello”);

 

To Look for a word in a divider / paragraph / span     using FireFox (if it does not find it, it returns null):

document.getElementById(“sample”).textContent.match(“Hello”);

 

To Set a Textbox / input / label / divider/ paragraph / span or anything else HIDDEN / INVISIBLE:

document.getElementById(“sample”).style.display = “none”;

 

To Set a Textbox / input / label / divider/ paragraph / span or anything else SHOW/ VISIBLE:

document.getElementById(“sample”).style.display = “block”;

 

Detect if browser is on iphone or ipad in C#

USING C#

if ((Request.ServerVariables[“HTTP_USER_AGENT”].Contains(“iPad”))

{

//Do Something for iPad

}

else if((Request.ServerVariables[“HTTP_USER_AGENT”].Contains(“iPhone”)))
{

//Do Something for iPone

}

 

USING JAVASCRIPT

if (navigator.userAgent.match(/iPad/i) == “iPad”))

{

//Do Something for iPad

}

else if(navigator.userAgent.match(/iPhone/i) == “iPhone”)
{

//Do Something for iPone

}

JavaScript Get Server Time

I once needed to check time on both server side and in JavaScript, but my problem was that the server was not in the same location I was testing my website so the JavaScript time and Server time in code behind did not match. Below is an easy way I used to go around this issue:

 

HTML PAGE / JavaScript:

<script type=”text/javascript”>

$(document).ready(function() {

var d = new Date();
var dateFromServer = $(‘#<%= lbl_serverTime.ClientID %>’).html(); //Get Time from Label which is loaded from Server (through Code Behind)
var time = dateFromServer.substring(11); //Takes only the time in hh:mm:ss format
var n = (d.getMonth()+1) + “/” + d.getDate() + “/” + d.getFullYear() + ” ” + time ;  //puts it together in MM/dd/yyyy hh:mm:ss format
var dateNow = new Date(n); //Created new date from Server Time

alert(dateNow);

});

</script>

 

<asp:Label ID=”lbl_serverTime” runat=”server” Text=””></asp:Label>

 

CODE BEHIND:

//Copy the method Page_Init in your code behind or add it to your Page_Init Method

protected void Page_Init(object sender, EventArgs e)
{

try
{

lbl_serverTime.Text = DateTime.Now.ToString(); //Sets Label to DateTime which is taken from Server

}
catch (Exception ex)

{

throw ex;

}

}

Javascript pass arguments to WebMethod in C#

So, as we all know WebMethod generally cannot access any other parts of the code since it is normally a static and a web method. Therefore I found a quick and silly idea to get around with this. I have set labels hiden in the page and I’m passing their content as an argument when calling the WebMethod. This is done as shown below through Ajax Calls:

HTML PAGE:

<script type=”text/javascript”>

$(document).ready(function() {

$.ajax({
type: “POST”,
url: “default.aspx/GetMyWebMethod”,
data: “{arg1:'” + $(‘#<%= lbl_myFirstArgument.ClientID %>’).html() + “‘,arg2:'” + $(‘#<%= lbl_mySecondArgument.ClientID %>’).html() + “‘}”,

contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function(msg) {
//Do something on success
}

});

});

</script>

 

<div style=”display: none”>

<asp:Label ID=”lbl_myFirstArgument” runat=”server” Text=””></asp:Label>
<asp:Label ID=”lbl_mySecondArgument” runat=”server” Text=””></asp:Label>

</div>

 

CODE BEHIND:

//We will fill the content of the labels in the Page_Init in order to be ready on document.ready(function() {} );

protected void Page_Init(object sender, EventArgs e)
{

lbl_myFirstArgument.Text = DateTime.Now.toString();

lbl_mySecondArgument.Text = “Write Something here or get something dynamically from Database to pass to WebMethod”;

}

[WebMethod]
public static void GetMyWebMethod(string arg1, string arg2)
{

//You Can do something with arg1 and arg2 

}

 

That’s All !!!! Please feel free to comment or give suggestions on quick and easy alternatives 🙂

JavaScript match vs trim

Both the match and the trim can be used as a substitute to string.contains() since JavaScript does not contain the property contains, however they work in different ways:

Match

docomunet.getElementById(‘myId’).textContent.match(‘stringToLookFor’);   // FireFox:  looks for the content ‘stringToLookFor’ in ‘myId’ text and returns true or false

docomunet.getElementById(‘myId’).innerText.match(‘stringToLookFor’);   // Chrome/IE:  looks for the content ‘stringToLookFor’ in ‘myId’ text and returns true or false

Trim

docomunet.getElementById(‘myId’).textContent.trim(‘stringToLookFor’);   // FireFox:  trims the text in myId to ‘stringToLookFor’ and is returned as string /var

docomunet.getElementById(‘myId’).innerText.trim(‘stringToLookFor’);   // Chrome/IE:   trims the text in myId to ‘stringToLookFor’ and is returned as string /var

Continue reading

JavaScript innerText property for Firefox (textContent)

The JavaScript commonly used innerText property functions well in chrome and internet explorer, however in firefox it has a different naming property called textContent:

document.getElementById(‘sample’).innerText = ‘NOT for firefox’;     //Chrome/IE

document.getElementById(‘sample’).textContent= ‘FOR firefox’;  //Firefox