Dynamically add button, textbox, input, radio elements in html form using JavaScript. Friday, Nov 4 2011 

Adding Elements like textbox, button, radio button etc in a html form using JavaScript is very simple. JavaScript’s document object has a method called createElement() which can be used to create html elements dynamically.

We had used this function in our tutorial: Dynamic combobox-listbox-drop-down using javascript to add dynamic options to a combo box-listbox. Let us use this function to create textboxes, radio buttons, buttons etc dynamically and add them in our page.

Following is the source code of our example.

 

<HTML>

<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function add(type) {
    //Create an input type dynamically.
    var element = document.createElement("input");
    //Assign different attributes to the element.
    element.setAttribute("type", type);
    element.setAttribute("value", type);
    element.setAttribute("name", type);
    var foo = document.getElementById("fooBar");
    //Append the element in page (in span).
    foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<SELECT name="element">
    <OPTION value="button">Button</OPTION>
    <OPTION value="text">Textbox</OPTION>
    <OPTION value="radio">Radio</OPTION>
</SELECT>
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar">&nbsp;</span>
</FORM>
</BODY>
</HTML>
Advertisements

Append text in TextArea at cursor location using Javascript Monday, Sep 19 2011 

I have a TextArea, textBox and a button. TextArea has some text e.g This is a cat.

Now my requirement is If someone set cursor position in TextArea and enter text in textbox and click on button the text should be append in cursor position instead of last. e.g.

TextArea: This is a cat.

Cursor position: after “a” Entered Text in TextBox: black

Output: This is a black cat.

 

function insertTextAtCursor(el, text) {
var val = el.value, endIndex, range;
if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
endIndex = el.selectionEnd;
el.value = val.slice(0, endIndex) + text + val.slice(endIndex);
el.selectionStart = el.selectionEnd = endIndex + text.length;
} else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
el.focus();
range = document.selection.createRange();
range.collapse(false);
range.text = text;
range.select();
}
}

 

That's it.

 

Random Image shuffle Javascript code Thursday, Apr 21 2011 

I tested the script and it’s perfect, only thing is I need the random images to load within a set table/cell. The ” onload=”ShufImages();” function needs to be confined within a set table/cell.

I’ve tried placing the function in the header but it errors.

Any help would be greatly appreciated.

Thanks in advanced.

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
http://www.w3.org/TR/html4/strict.dtd”&gt;
<html>
<head>
<title></title>
<script language=”JavaScript” type=”text/javascript”>
<!–
var ImgPath=’/StdImages/’;
var ImgAry=new Array(‘One.gif’,’Two.gif’,’Three.gif’,’Four.gif’,’Five.gif’);
var RandomNu;
var ImgCnt=1;
function ShufImages(){
while (ImgCnt<ImgAry.length){
RandomNu=Math.floor(Math.random()*(ImgAry.length-1));
if (ImgAry[RandomNu]!=’X’){
document.getElementById(‘I’+ImgCnt).src=ImgPath+ImgAry[RandomNu];
ImgAry[RandomNu]=’X’;
ImgCnt++;
}
}
}
//–>
</script>
</head>
<body onload=”ShufImages();” >
<table width=”400″ border=”1″ >
<tr>
<td>
<img id=”I1″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
<td>
<img id=”I2″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
<td>
<img id=”I3″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
<td>
<img id=”I4″ src=”/StdImages/Blank.gif” width=”100″ height=”100″>
</td>
</body>
</html>

Very simple example of Javascript sleep method Tuesday, Apr 12 2011 

Have you ever needed the sleep command in JavaScript? Usually you can use the existing setTimeout(), clearTimeout() and setInterval() to accomplish what you want and in those cases you should use the native functions. But if you really need the sleep or wait statement lets go through the options and see what code might work the best.

JavaScript sleep by loop

<script type="text/javascript">
// bad implementation
function sleep(milliSeconds){
	var startTime = new Date().getTime(); // get the current time
	while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
</script>
We are using a while loop on line 3 that continually
 evaluates the current time against the time when
 we should stop blocking. This loop will run as fast
 as the browser will let it all the while using up 
valuable cpu resources. Checking the time might not 
seem like much but doing it thousands (or tens of thousands) 
of times per second make a noticeable performance impact 
on your computer (try it and watch your cpu meter). 
This code will "pause" your thread but will also use
 all the resources your computer will give it.
Resource taken from:
http://www.devcheater.com/

 

Traversing inside a div/table content using Javascript Monday, Dec 13 2010 

Here is the code to get element inside a div/table and number of div/table or table inside a div/table.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<head>
<title></title>
<script type=”text/javascript”>
function foo(divId1) {
var divId = document.getElementById(“div1”);
var divs = divId.getElementsByTagName(“div”);
alert(“number of div inside div1” + divs.length);
for (var i = 0; i < divs.length; i++) {
divs[i].style.display = “none”;
}
document.getElementById(divId1).style.display = “block”;
}
</script>
</head>
<body>
<div id=”div1″>
<div id=”id1″>Here is Div 1 data.</div>
<div id=”id2″>Here is Div 2 data.</div>
</div>
<input type=”button” value=”Click Me1″ onclick=”foo(‘id1’)” />
<input type=”button” value=”Click Me2″ onclick=”foo(‘id2’)” />
</body>
</html>

Get URL Parameters (QueryStrings) using Javascript Wednesday, Nov 10 2010 

Nearly all server-side programming languages have built-in functions to retrieve querystring values of a URL. In web browsers you can access the querystring with client-side JavaScript, but there is no standard way to parse out the name/value pairs. So here is afunction to return a parameter you specify. The following javascript code snippet facilitates Javascript’s built in regular expressions to retrieve value of the key. Optionally, you can specify a default value to return when key does not exist.

function getQuerystring(key, default_)
{
if (default_==null) default_=””;
key = key.replace(/[\[]/,”\\\[“).replace(/[\]]/,”\\\]”);
var regex = new RegExp(“[\\?&]”+key+”=([^&#]*)”);
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}

The getQuerystring function is simple to use. Let’s say you have the following URL:

http://www.bloggingdeveloper.com?author=bloggingdeveloper

and you want to get the “author” querystring’s value:

var author_value = getQuerystring(‘author’);

 

Reference: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx

How to create a simple class in Javascript with Hello world Example Monday, Oct 25 2010 

Hello, world!

JavaScript OOP Tutorial: Classes

This is a JavaScript DOM exercise from Chapter 3 of Microsoft AJAX Library Essentials: JavaScript in ASP.NET AJAX 1.0 Explained.

Not only that JavaScript functions can contain other functions, but they can also be instantiated. This makes JavaScript functions a good candidate for implementing the concept of class from traditional object-oriented programming. This is very helpful feature indeed, because JavaScript doesn’t support the notion of class in the classic sense of the word. Functions can be instantiated using the new operator, such as in this example:

var myHelloWorld = new ShowHelloWorld();

This line of code effectively creates an object named myHelloWorld, which represents an instance of the ShowHelloWorld() function. When the object is instantiated, the function code is executed, so creating the object has the same effect as calling ShowHelloWorld() like in the previous examples.

Here are a few facts that will help you port your C# OOP knowledge into the JavaScript world:

  • When a function is used as a class, its body code is considered to be the constructor. In classic OOP, the constructor is a special method that doesn’t return anything, and that is called automatically when the object is created. The same effect happens in JavaScript when creating an instance of the function: its code executes. A C# constructor is equivalent with the code in the JavaScript function – without including any inner functions (whose code doesn’t execute automatically).
  • In C# constructors can receive parameters, and also in JavaScript. If the code in a function represents the “class constructor”, the parameters received by that function play the role of constructor parameters.
  • Class fields in JavaScript are created and referenced with the this keyword. In a JavaScript function, this.myValue is a public member of the function (class), while myValue is a local variable that can’t be accessed through function instances. Also, the local variable is destroyed after the function executes, while class fields persist their value for the entire object life time.
  • Class methods that need to be accessible from outside the class need to be referred using this as well. Otherwise the inner function will be regarded as a local function variable, rather than a “class” member.

We’ll demonstrate these concepts by transforming the ShowHelloWorld() function that you saw earlier into a “real” class. We will:

  • Change the name of the function from ShowHelloWorld() to HelloWorld().
  • Add a parameter named hour to the function’s “constructor” so that we tell the class the hour for which we need a greeting message, when instantiating it. If this parameter is passed when creating objects of the class, we store it for future use as a class field. If this parameter is not specified, the current hour of the day should be stored instead.
  • The method DisplayGreeting() of the class should not support the hour parameter any longer. Instead, it should display the greeting message depending on the hour field that was initialized by the constructor.

TIP. Why are we changing the name of the function? Remember, OOP is a style of coding, not a list of technical requirements that a language must support. JavaScript is considered as an OOP-capable language because it supports an object-based programming style. In the OOP paradigm, a class should represent an entity, and not an action. Since we intend now to use ShowHelloWorld() as a class, we are changing its name to one that reflects this purpose.

Once your new class is created, you use it just like you’d use a C# class. For example, this is how you’d create a new class instance, and call its DisplayGreeting() method:

// create class instance
var myHello = new HelloWorld();

// call method
myHello.DisplayGreeting();

A possible implementation of the HelloWorld class is the following.

// "Hello, World" class
function HelloWorld(hour)
{
  // class "constructor" initializes this.hour field
  if (hour)
  {
    // if the hour parameter has a value, store it as a class field
    this.hour = hour;
  }
  else
  {
    // if the hour parameter doesn't exist, save the current hour
    var date = new Date();
    this.hour = date.getHours();
  }

  // display greeting
  this.DisplayGreeting = function()
  {
    if (this.hour >= 22 || this.hour <= 5) 
      document.write("Goodnight, world!");
    else
      document.write("Hello, world!");
  }  
}

The HelloWorld class is formed of the constructor code that initializes the hour field (this.hour), and of the DisplayGreeting method – this.DisplayGreeting(). Fans of the ternary operator can rewrite the constructor using this shorter form, which also makes use of the object detection feature that was discussed in Chapter 2:

  // define and initialize this.hour
  hour = (hour) ? hour : (new Date()).getHours();

TIP: The ternary operator is supported both by C# and JavaScript. It has the form (condition ? valueA : valueB). In case the condition is true, the expression returns valueA, otherwise it returnsvalueB. In the shown example, object detection is used to test if a value was supplied for the hour parameter. If it was not, the current hour is used instead.

Implement the exercise step by step and find detailed explanations in our book, Microsoft AJAX Library Essentials: JavaScript in ASP.NET AJAX 1.0 Explained.

Reference: http://www.cristiandarie.ro/asp-ajax/JavaScriptClass.html

How to detect browsers using javascript Monday, Oct 25 2010 

There is a very simple approach to detecting the browser name using java script:

function detect_browser()
{
var browser_name = navigator.userAgent;
// We have to check for Opera first because
// at the beginning of the userAgent variable
// Opera claims it is MSIE.

if (browser_name.indexOf(“Opera”)!= -1)
browser_name = “Opera”;
else if (browser_name.indexOf(“Firefox”)!= -1)
browser_name = “Firefox”;
else if (browser_name.indexOf(“MSIE”)!= -1)
browser_name = “MSIE”;
else if (browser_name.indexOf(“Netscape”)!= -1)
browser_name = “Netscape”;
else if (browser_name.indexOf(“Safari”)!= -1)
browser_name = “Safari”;

alert(browser_name);

} // end function detect_browser()

How to get HTML table data without knowing the table id/name using javascript Friday, Oct 22 2010 

In this article I will show you how to fetch data from a table without knowing the table id or table name from a page.

It’s rather easy but when I face this problem it takes too long to resolve it.

So let’s start from HTML content. Suppose we have two table in our page we wants to traverse a particular table which doesn’t have id. The HTML content looks like:

<body onLoad=”GetTdContent();”>
<div id=”div1″>
<table border=”1″>
<tr>
<td>Name</td>
<td>Designation</td>
<td>Company Name</td>
</tr>
<tr>
<td>ABCD</td>
<td>Software Engineer</td>
<td>Microsoft</td>
</tr>
<tr>
<td>WXYZ</td>
<td>Manager</td>
<td>Oracle</td>
</tr>
<tr>
<td>PQRS</td>
<td>Salesman</td>
<td>Google</td>
</tr>
</table>
</div>
<table border=”1″>
<tr>
<td>Name</td>
<td>Designation</td>
<td>Company Name</td>
</tr>
<tr>
<td>ABC</td>
<td>Software Engineer</td>
<td>Infosys</td>
</tr>
<tr>
<td>XYZ</td>
<td>HR Manager</td>
<td>TCS</td>
</tr>
<tr>
<td>PQR</td>
<td>Salesman</td>
<td>HCL</td>
</tr>
</table>
</body>

Here we have two tables and we are calling a method(GetTdContent) on body load event. I think nothing is special here.

Now let’s go thru javascript code of this:

<script language=”javascript”>
function GetTdContent()
{
var theDivElement = document.getElementById(“div1”);
var Tables = theDivElement.getElementsByTagName(“table”);
alert(Tables.length);
var foundFlag = false;
if (theDivElement != null)
{
if(Tables.length > 0)
{
var TRs = Tables[0].getElementsByTagName(“tr”);
for (var j = 0; j < TRs.length; j++)
{
if(j == 0)
{
var TDs = TRs[j].getElementsByTagName(“td”);
var headVariable = “”;
for (var i = 0; i < TDs.length; i++)
{
headVariable += TDs[i].innerHTML + ”  “;
}
alert(headVariable + ” “);
}
else
{
var elementVariable = “”;
var TDs = TRs[j].getElementsByTagName(“td”);
for (var i = 0; i < TDs.length; i++)
{
elementVariable += TRs[j].getElementsByTagName(“td”)[i].innerHTML + ”  “;
}
alert(elementVariable);
}
}
}
}
}
</script>
That’s it.

 

Creating popup page using javascript Tuesday, Oct 19 2010 

Creating popup page using javascript. Code snippet is:
function PopUp(page)
{
	winx=window.open(page,'','width=415,height=165,toolbar=no,location=yes,directories=no,status=yes,scrollbars=no,resizable=yes,copyhistory=yes');
	winx.focus();
}

Next Page »