Archive for the Javascript Codes Category

Using if – else in Javascript

The following if – else conditions in javascript:

  • if statement – simple if statement, executed when condition is true
  • if…else statement – statements are executed when condition is true or false
  • if…else if….else statement -  nested if – else statement which can b used for multiple blocks of code
  • switch statement -  simplified nested if – else statement

Syntax

if statment:

if (condition)
{
code to be executed if condition is true
}

if – else statement:

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

nested if – else statement:

if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}

switch statement:

switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

Getting mac address using Javascript

Here is a sample code on how to extract the mac address of a computer using the powerful javascript.  The code will only work for internet explorer only.

<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Getting MAC Address From Javascript(IE Only)</title>

<script language=”javascript”>
function showMacAddress(){

var obj = new ActiveXObject(“WbemScripting.SWbemLocator”);
var s = obj.ConnectServer(“.”);
var properties = s.ExecQuery(“SELECT * FROM Win32_NetworkAdapterConfiguration”);
var e = new Enumerator (properties);

var output;
output=’<table border=”0″ cellPadding=”5px” cellSpacing=”1px” bgColor=”#CCCCCC”>’;
output=output + ‘<tr bgColor=”#EAEAEA”><td>Caption</td><td>MACAddress</td></tr>’;
while(!e.atEnd())

{
e.moveNext();
var p = e.item ();
if(!p) continue;
output=output + ‘<tr bgColor=”#FFFFFF”>’;
output=output + ‘<td>’ + p.Caption; + ‘</td>’;
output=output + ‘<td>’ + p.MACAddress + ‘</td>’;
output=output + ‘</tr>’;
}

output=output + ‘</table>’;
document.getElementById(“box”).innerHTML=output;
}
</script>

</head>
<body>
<input type=”button” value=”Show MAC Address” onClick=”showMacAddress()” />

<div id=”box”>
</div>
</body>
</html>