For Developers
Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

How to view source of a show modal dialog page

We can view a page source normally from the menu view->source in mozilla or ie.But how would we view a page source of a showmodal page.

we can achieve it by the following code.


function viewSource()

{

d=window.open();
d.document.open('text/plain').write(document.documentElement.outerHTML);
return false;

}

How to read XML using Javascript?

The Document Object Model (DOM) as implemented in MSXML provides a programmatic representation of XML documents, fragments, nodes, or node-sets. It also provides an application programming interface for working with XML data.

The following JScript fragments outline the basic process of programming with XML DOM.


var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");


Example:


function loadXML(xmlFilePath)
{
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try //Firefox, Mozilla, Opera, etc.
{
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e)
{
alert(e.message)
}
}
try
{
xmlDoc.async=false;
xmlDoc.load(xmlFilePath); // xmlFilePath - xml file path Ex: test.xml
return(xmlDoc);
}
catch(e)
{
alert(e.message)
}
return(null);
}

setInterval Method in Javascript

The setInterval() method evaluates a function or an expression repeatedly for the specified number of milliseconds and it returns an interval reference.

Syntax:


variable = setInterval(expression, milliseconds)
or
variable = setInterval(function, milliseconds)

variable holds the interval reference returned by seInterval method


Example:
Below example display the current time information using setInterval method call the date object.

< html>
< head>
< title> setInterval Method Example </title>
< script language="javascript">
function startSetInt()
{
ref=setInterval("init()",100);
}

function init()
{
dt = new Date();
document.getElementById("lbl").innerText = "Timer : " + dt;
document.getElementById("btnStart").disabled = true;
document.getElementById("btnStop").disabled = false;
}

function stopSetInt()
{
clearInterval(ref)
document.getElementById("lbl").innerText = "Timer : ";
document.getElementById("btnStart").disabled = false;
document.getElementById("btnStop").disabled = true;
}
</script>
</head>
< body onload="startSetInt()">
< label id="lbl" name="lbl"></label>
</br>
</br>
< input type="button" id="btnStart" value="Start" onclick="startSetInt()" />
< input type="button" id="btnStop" value="Stop" onclick="stopSetInt()" />
</body>
</html>

Demo : Click here

JSON Data types and Example

The following are the Basic JSON Data types,


  • Number : integer, real, or floating point
  • String : double-quoted Unicode with backslash escaping
  • Boolean : true and false
  • Array : an ordered sequence of values, comma-separated and enclosed in square brackets
  • Object : collection of key:value pairs, comma-separated and enclosed in curly braces
  • null


Example


{
"firstName": "Praveen",
"lastName": "C",
"address": {
"streetAddress": "KK Nagar",
"city": "Chennai",
"state": "TN",
"postalCode": 6310102
},
"phoneNumbers": [
"091 98943 37266"
]
}

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

Split Function in Javascript

Split Function: Delimiter :-
The space character " " we mentioned will be our delimiter and it is used by the split function as a way of breaking up the string. Every time it sees the delimiter we specified, it will create a new element in an array. The first argument of the split function is the delimiter.

Split() Function:-
The split() function splits text and puts the pieces into an array, with each piece taking up one slot in the array. For example, if you were to split "This is some text",the split() function would create an array with four slots (zero to 3). The first slot in the array would contain "This", the second slot would contain "is", the third "some" and the fourth "text".

Example:-



var stringdata= "1$2$3$4";

var splitdata = stringdata.split("$");

for(i = 0; i < splitdata .length; i++)
{
document.write("Element " + i + " = " + splitdata [i]);
}
Output
=====
Element 0 = 1
Element 1 = 2
Element 2 = 3
Element 3 = 4


Date Function in Javascript

1.create a date object and store it in a variable


var d= new Date();

2.Using the date object,Get the hour,minute,second,month,dayofmonth and year of the Current Date



var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
var month = d.getMonth();
var dayofmonth = d.getDate();
var year = d.getYear();

Example:-
Display Next Day of Today


function getNextDate()
{
var date= new Date();
var day = date.getDate();
var month = date.getMonth();
var year = date.getYear();

var nextdate= new Date(year, month, day +1);
var nxtDate=nextdate.getMonth()+1+"/"+nextdate.getDate()+"/"+NextDate.getYear();
document.getElementById('DisplaynextDate').value=nxtDate;
//Display Next Date(today+1)
}


Disable Right Mouse Click Using JavaScript

Disable Right Mouse Click Using JavaScript:

Description:

This script will prevent the default right menu from popping up when the right mouse is clicked on the web page. Works well in IE4+ and NS4+.

To use this script, paste the following code in the <body> section of your HTML document.


Disable right click on mouse


Function to handle right click if the browser is IE

<script language="JavaScript">

var message=”Right Click is Disabled”;

function ExeForIE()
{
if (event.button==2)
{
alert(message);
return false;
}
}

</script>


Function to handle right click if the browser is FireFox

<script language=JavaScript>

var message=”Right Click is Disabled”;

function ExeForFFox(evt)
{
if (document.layersdocument.getElementById&&!document.all )
{
if (evt.which==2evt.which==3)
{
alert(message);
return false;
}
}
}

if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = ExeForFFox;
}
else if (document.all&&!document.getElementById)
{
document.onmousedown = ExeForIE;
}

document.oncontextmenu=new Function(”alert(message);return false”)

</script>


Block JavaScript Errors

We can have a function with return true and use it on window.onerror.Thus when the browser encounters a JavaScript error it returns true and block the error begin displayed.


function blkError()
{
return true;
}

window.onerror = blkError;

Add a Row Dynamically using JavaScript

How to Add a Row Dynamically Using JavaScript:

  • We can see how button,textbox,textarea can be added Dynamically
  • All the tag which can be given in the input tag has to be given in setAttribute as shown in below coding
  • if u call a function then call as but1.onclick = function () {show(this)};
  • If u delete the Row,then reorder all the other row
1.If u Add a Button to a Table,then use this


var cell1 = row.insertCell(0);
but1 = document.createElement('input');
but1.setAttribute('type', 'button');
but1.setAttribute('className', 'button');
but1.setAttribute('value', '');
but1.onclick = function () {show(this)};
cell1.appendChild(but1);


2.If u Add a Textbox to a Table,then use this


var cell2 = row.insertCell(1);
var txt = document.createElement('input');
txt.setAttribute('type', 'text');
txt.setAttribute('name', 'firsttextbox');
txt.setAttribute('className', 'text_box');
txt.setAttribute('id', 'firsttextbox' + iteration);
txt.setAttribute('size', '21');
cell2.appendChild(txt);


3.If u Add a Textarea to a Table,then use this


cell1 = row.insertCell(1);
var e1 = document.createElement('textarea');
e1.name = 'text2' + iteration;
e1.id = 'text2' + iteration;
e1.column= '50';
cell1.appendChild(e1);


4.Row can be Re-Order by using


var tbl = delRow.parentNode.parentNode;
tbl.tBodies[0].rows[i].myRow.two.id = 'firsttextbox' + count;


If u Delete 3 Row the Reorder as
4th Row as----3th Row
5th Row as----4th Row
6th Row as----5th Row

5.If u want to Delete the Third Row,then use this coding


var delRow = obj.parentNode.parentNode;
var rowArray = new Array(delRow);
for (var i=0; i<rowObjArray.length; i++) {
var rIndex = rowObjArray[i].sectionRowIndex;
rowObjArray[i].parentNode.deleteRow(rIndex);
}


  • We have to pass all the id in the row as deleterow(this)
  • this can be get in the obj variable
  • Using the For Loop we have to Delete the Particular Row




Demo Link

Javascript compare two numbers

How to compare two Value in JavaScipts:

1.Get the Value From Html Page using getElementById

2.Compare by Using parseInt For Interger Value and parseFloat For Float Value

3.compare two value as


var first=document.getElementById('first').value;
var second=document.getElementById('second').value;

if(parseInt(first)<parseInt(second))
alert('Second Value is Greater than first');

else if(parseInt(first)>parseInt(second))
alert('First Value is Greater than second');

else if(parseInt(first)==parseInt(second))
alert('First Value and second value is equal');


4.Include the code in Html Page For TextBox

First Value:<input type="text" value="0" onkeyup="compare();" name="first" id="first">
Second Value:<input type="text" value="0" onkeyup="compare();" name="second" id="second">



Demo Link

JavaScript to Validate Email Format

Script :


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

function checkEmailFormat(field,msg)
{
var ctrl=document.getElementById(field);
if((!efmt.test(ctrl.value)) && ctrl.value!=”)
{
alert(msg);
ctrl.focus();
}
}

Html Code :


< type=”Text” onblur=”checkEmailFormat(’Txtemail’,'Please enter a valid email address, like sample@yahoo.com’);” id=”Txtemail” />


Demo Link

set focus on textbox value at the end

Set focus on textbox Value at the End using javascript:

1.Search is a variable that can be given in id for the TextField.
2.setFocus() Method can be call in onload.
3.The Cursor will point at the End of the Value
(if any value Present it will point at the end of the value)


function setFocus()
{
var field = document.form.Search;
field.focus();
field.value = field.value;
field.focus();
}


Demo Link

Refresh the Window

using JavaScript,Refresh the Window or Reset the Window


window.location.reload();

JSP Applet tag

How to Include Applet Program in a JSP Page:

1.Create a Applet Java Program

sample.java


import javax.swing.JApplet;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class sample extends Applet {

sampleCanvas canvas; // The drawing area to display arcs
public static String s=null;

public void init() {
setLayout(new BorderLayout());
canvas = new sampleCanvas();
add("Center", canvas);
s=this.getParameter("data");
}

public void destroy() {
remove(canvas);
}

public void start() {
}

public void stop() {
}

public void processEvent(AWTEvent e) {
if (e.getID() == Event.WINDOW_DESTROY) {
System.exit(0);
}
}

}

class sampleCanvas extends Canvas {
font = new java.awt.Font("SansSerif", Font.PLAIN, 12);

public void paint(Graphics g) {
Rectangle r = getBounds();

if(sample.s==null)
sample.s="0";
int a = Integer.parseInt(sample.s);
a=(a*600)/1000;

g.fillRect(10, 200,a, 25);

}

public void redraw(int value) {
this.filled = filled;
this.startAngle = value;
repaint();
}
}


2.Complie the Applet Program

3.Import the applet Program in the JSP File

<%@page import="com.sample"%>


4.Include this Tag in the JSP File

<jsp:plugin type="applet" code="sample.class" width="620" height="450">
<jsp:params>
<jsp:param name="data" value="10"/>
</jsp:params>
</jsp:plugin>

Set textbox background color when clicked

To set the background color of the textbox, use the 'backgroundColor' property.
eg.


< input type="text" style='background:#fce09a' value='www.fordevs.com >

If you want to set the background color on text focus then use the 'onfocus' event.

The following example illustrates you how to set the color in 'onfocus' event. When the texbox loses the focus then normal background color is retained.


<html>
<body>
<br><input type="text" onfocus="this.style.backgroundColor='#fce09a';value=''"

onblur="this.style.backgroundColor='#ffffff';if(value==''){value='[Enter your

name]'} " accesskey="s" value='[Enter your name]' name="searchtextbox"

id="searchtextbox" style="color: rgb(0, 0, 0); background-color: rgb(255, 255,

255); outline-color: rgb(255, 0, 0); outline-style: solid; outline-width: 1px;"

class="searchInput" autocomplete="off"/>
<br>
</html>

Demo link