Wednesday, May 5, 2010

Regular Expression (Regex)

This link has good material about Regular Expression (Regex) in Javascripts.



The test() function of the RegExp object is a shortcut to exec() != null. It takes the subject string as a paarameter and returns true or false depending on whether the regex matches part of the string or not.

You can call these methods on literal regular expressions too. /\d/.test(subject) is a quick way to test whether there are any digits in the subject string.

Example:

var patternAbcLoan= /^Abc Loan/;

if(patternAbcLoan.test("Abc Loan is right")) {

alert('Passed');

}

Wednesday, March 4, 2009

AJAX Framework

AJAX Frameworks

1. Prototype
2. JQuery
3. Scriptaculous
4. Dojo

Google Web Toolkit (GWT) and Yahoo! User Interface (YUI)

Tuesday, August 5, 2008

Getting the focus back to pop-up window

In an web page on click of a button, we are getting a pop-up e-mail window. User can minimize the window and proceed with the application. We need to ensure, whenever user minimizes the window we need give an appropriate message and bring the focus back to the pop-up window.

var letterWindow;
function insufficientLimit()
{
letterWindow=window.open('insufficientLimit.do?bankKey='+cell1.childNodes[0].data+'&bankFacilityKey='+cell.childNodes[0].data,'printFriendlyView','resizable=1,width=790,height=550,status=1,scrollbars=yes');
}

function checkPopup() {
if(letterWindow != null && letterWindow.closed == false) {
alert("Please Send/Close the letter if you want to proceed");
letterWindow.focus();
}

On the parent JSP page (From where the pop-up window comes) we need to call the checkPopup() function
So when ever the user minimizes the pop-up window or clicks the parent window when the child (pop-up) window is open, the focus comes to parent window and we invoke the javascript function to get the focus back to the child (pop-up) window.
<body onfocus="checkPopup();">

One other way of doing the same is

<script type="text/javascript">
document.onmousedown=checkPopup;
</script>
</head>
<body>

Here only when the user clicks anywhere (button/text/link/etc) in the parent window we invoke the javascript function to get the focus back to the child (pop-up) window.

Related Links

Link-I

Link-II

Thursday, July 31, 2008

How to get the URL of the web page from a javascript?

var protocol = document.URL.split("//");
var urlParts = protocol[1].split("/");
var url = protocol[0]+"//"+urlParts[0]+"/"+urlParts[1]+"/app/RefreshServlet";
Protocol: http:, localhost:7001/GTEMWeb/app/searchRequest.do?
urlParts: localhost:7001, GTEMWeb, app, searchRequest.do?
protocol[0]: http:
urlParts[0]: localhost:7001
urlParts[1]: GTEMWeb
urlParts[2]: app

Tuesday, July 29, 2008

innerText, innerHTML, outerHTML

The below links help us understand better on how to access data using Javascript.

Link-I

Link-II

Link-III

How to get the html source of a jsp page and set it to a property of a form?

var htmlSource = document.getElementById("htmlSource");
htmlSource.value = document.documentElement.outerHTML;

Tuesday, May 20, 2008

showModelessDialog – Build-in javascript function.


Difference between model and modeless dialog window.

Model Dialog Window prevented user access to the main window until the dialog window closes.
Modelless Dialog Window always stays in front of the main window, but allows access to the main window's user interface elements.

The methods called
1. window.showModalDialog() and
2. window.showModalessDialog()

We will start by designing the session timeout mechanism for a standard small to medium sized web application.

We set the session timeout in web.xml as 20 minutes. We pass this info through the tiles parent(Main) page to the javascript build-in function. After 15 minutes we give the user a pop-up message about the session timeout in another 5 minutes with Yes/No options. If user clicks Yes, then the session gets refreshed and starts from the beginning. For No in another 5 minutes the session is destroyed.

We set the web app session time-out in web.xml

web.xml

<session-timeout>20</session-timeout>

Menu.jsp

We call the function setTimer() from Menu.jsp (This is the Tiles JSP Page where we pass the original page as body using tiles along with header and footer information. Immediately after every page loads we pass the session time-out seconds to setTimer function for calculation.)

<script type="text/javascript">
setTimer(<%=request.getSession().getMaxInactiveInterval()%>);
</script>

Session timeout Requirement

Total user active session time is 20 minutes.

First pop-up at 15 minutes, (No response (or) No from user), second pop-up after 5 minutes indicating the user session has expired.

1 - When first alert opens, give Yes/No buttons.
2 - If the user hits YES we retart the timer and make a call on the web application so it will maintain the session longer.
3 - if user hits No, or does not hit any button and the second alert pops-up, cancel the session like you currently are and just before the second pop-up shows up close the first pop-up.
In this way even if the user clicks NO @ 18th minute session should be killed @ 20th minute instead of extending 5 minutes from 18th minute.

Common.js

To convert seconds to milliseconds we multiply by 1000. We pass 1200 seconds (20 minutes) to setTimer function. In setTimer() function using setTimeout() built-in function we invoke notification1() function after 15 minutes.

// Input to setTimer function is from Menu.jsp page which is 20 minutes (20 * 60 = 1200 seconds).
// We multiply with 1000 to get milliseconds. we multiply by (3/4 = 0.75) to get 15 minutes, when we give the
// first notification message to user along with option to refresh the session.

var sessiontime;
var n2;

function setTimer(sessiontimeout)
{
if (sessiontimeout!= null)
{
sessiontime = sessiontimeout*1000;

// sessiontime = 1200 * 1000 = 1200000 * 0.75 = 900000 milliseconds = 900 seconds = 15 min
var Id1= setTimeout("notification1()",sessiontime*(3/4));
}
}

var wn1;

function notification1() {
var params = new Object();
params.confirmationMsg = "The system has not registered any recent activity. In 5 minutes this connection will timeout as a security feature, unless there is some user input. Data Not Saved will be lost at that time. \n\n To continue this session, click Yes";
params.button1Display = " Yes ";
params.button2Display = " No ";
params.button1Action = resetSessionExpiry;
params.button2Action = setSessionExpiry;
params.button1Visibility = "visible";
params.button2Visibility = "visible";
var url = "../jsp/common/jsp/ExpiredSessionMsg.jsp";

//window.showModelessDialog() returns a window object reference

wn1=showModelessDialog(url,params,"dialogWidth:500px; dialogHeight:250px; status:no; center:yes;help:no");

setNotification2();
}

The third parameter in showModelessDialog() is used to get the pop-up window in the center of the page.

function notification2() {

if(wn1 != null) {
wn1.close();
}

var params = new Object();
params.confirmationMsg = "This session has timed out as a security measure. Unsaved data are not retained"
params.button1Display = " OK ";
params.button2Display = "Cancel";
params.button1Action = dummy;
params.button2Action = dummy;
params.button1Visibility = "visible";
params.button2Visibility = "hidden";
var url = "../jsp/common/jsp/ExpiredSessionMsg.jsp";
showModelessDialog(url,params,"dialogWidth:500px; dialogHeight:250px; status:no; center:yes;help:no");
}

/*
The setTimeout method is available on window objects.
It is used to add a delay to a function (usually one that is going to be executed multiple times.
*/

/*
The clearTimeout method is available on window objects.
It is used to clear a delay to a function that was set using setTimeout().
*/

function resetSessionExpiry(){

clearTimeout(n2);
if (sessiontime!= null)
{
var Id2= setTimeout("notification1()",sessiontime*(3/4));//15 mints==60000*15=900000
//If the user clicks Yes, Reload the page without Refreshing the browser.
var protocol = document.URL.split("//");
var urlParts = protocol[1].split("/");
var url = protocol[0]+"//"+urlParts[0]+"/"+urlParts[1]+"/app/RefreshServlet";
var req3;
if (typeof XMLHttpRequest != "undefined")
{
req3 = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req3 = new ActiveXObject("Microsoft.XMLHTTP");
}
req3.open("GET", url, true);
req3.onreadystatechange = dummy;
req3.send(null);
}
}


function setSessionExpiry(){
//clearTimeout(n2);
//setTimeout("notification2()",sessiontime*(1/4));//5mints === 60000*5=300000
}
function setNotification2(){
n2 = setTimeout("notification2()",sessiontime*(1/4));//5mints === 60000*5=300000
}
function dummy(){
}

ExpiredSessionMsg.jsp

window.dialogArguments:
Whatever parameter that is passed to the params
var params = new Object(); // This Object where we set the paramaters in notification1 and 2
// in common.js
become the dialogArguments property of the window object in the HTML that is being displayed.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script type="text/javascript" src="../jsp/request/js/common.js">
</script>
<script type="text/javascript">

var args = window.dialogArguments;
function display()
{

var confirmationMsg = document.getElementById("confirmationMsg");
confirmationMsg.innerText = args.confirmationMsg;
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
button1.value = args.button1Display;
button2.value = args.button2Display;
button1.style.visibility=args.button1Visibility;
button2.style.visibility=args.button2Visibility;
button1.onclick=args.button1Action;
button2.onclick=args.button2Action;
}

</script>
</head>

In the display() function we are setting the visibility style as well. Here is the link which talks more about setting the style property using Javascript.

<body onLoad="display();" style="background-color:#DEDFDE"; >
<p><b id="confirmationMsg" > </b> </p>

<p> <br><br>
<%for(int i=0;i<50;i++){ %> <%}; %>
<input class="primarybutton" id="button1" align="middle" onmouseup="window.close();" type="button" value="" />

<input class="primarybutton" id="button2" align="middle" onmouseup="window.close();" type="button" value="" /> </p>
</div>

</body>
</html>

Version-II
------------


var sessiontime;
function setTimer(sessiontimeout)
{
if (sessiontimeout!= null)
{
sessiontime = sessiontimeout*1000;
var Id1= setTimeout("notification1()",sessiontime*(3/4));//15 mints==60000*15=900000
}
}
function notification1() {
var params = new Object();
params.confirmationMsg = "The system has not registered any recent activity. In 5 minutes this connection will timeout as a security feature, unless there is some user input. Data Not Saved will be lost at that time.";
var url = "../jsp/common/jsp/ExpiredSessionMsg.jsp";
showModelessDialog(url,params,"dialogWidth:400px; dialogHeight:225px; status:no; center:yes;help:no");
setTimeout("notification2()",sessiontime*(1/4));//5mints === 60000*5=300000
}

function notification2() {
var params = new Object();
params.confirmationMsg = "This session has timed out as a security measure. Unsaved data are not retained"
var url = "../jsp/common/jsp/ExpiredSessionMsg.jsp";
showModelessDialog(url,params,"dialogWidth:400px; dialogHeight:225px; status:no; center:yes;help:no");
}


<script type="text/javascript">

var args = window.dialogArguments;
function display()
{
var confirmationMsg = document.getElementById("confirmationMsg");
confirmationMsg.innerText = args.confirmationMsg;
}

ExpiredSessionMessage JSP

</script>

</head>
<body onLoad="display();" style="background-color:#DEDFDE"; >
<div id="confirmBox">
<p><b id="confirmationMsg" > </b> </p>
<p> <br><br>


<input type="button" class="primarybutton" id="button1" value=" OK " align="middle" onclick="window.close();" />
</div>

</body>
</html>

Monday, May 5, 2008

Resetting the drop-downs (3 Drop - Downs)

Requirement:
We have 3 drop downs each containing the same values. If user selects one value (Search Criteria) in the first drop-down then he shouldn’t select the same in the next drop down. If the user selects the same value, then we need a throw a pop-up message saying this value is already selected and reset the drop down to default value.


<html:select size="1" property="advSearchCriteria1" name="RequestForm" styleClass="rmt-formTxt" style="margin-right:6px;" onchange="selectAdvSearchCriteria1();">
<html:option value="">Search Criteria1</html:option>
<logic:present name="RequestForm" property="searchDropList">
<bean:define id="row" name="RequestForm" property="searchDropList" />
<html:options collection="row" property="code" labelProperty="display" />
</logic:present>
</html:select>

function selectAdvSearchCriteria3()
{

var criteria1=document.forms[0].advSearchCriteria1.value;
var criteria2=document.forms[0].advSearchCriteria2.value;
var criteria3=document.forms[0].advSearchCriteria3.value;

if(criteria3 != '' && ((criteria3 == criteria1 ) (criteria3 == criteria2)))
{
alert("Already selected ");
document.forms[0].advSearchCriteria3.selectedIndex=0;
}
}

In the above function advSearchCriteria1 is a string property which will holds the selected search criteria by the user. Similarly we get the values of other drop-downs as well.

Wednesday, March 5, 2008

How to break lengthy lines

Tutorial:http://www.css3.com/css-word-break/

<td width="60%" style="word-break: break-all;"><bean:write name="ABCForm" property="description" /></td>

Description: "word-break: break-all" is a CSS style property which helps in bringing lengthy lines which doesn't have breaks(spaces) to next line. We can define it in an independant CSS file(wrap.css) as well and include it in our jsp pages.

This how we include the independant CSS file into our JSP Page.
<link rel="stylesheet" type="text/css" href="../css/wrap.css">

In the below independant css, we are specifying the style property for all the TD's. This means all the TD's which have a width property specified will obey this CSS Style.

wrap.css
--------
@CHARSET "ISO-8859-1";
TD {
word-break: break-all;
}

Wednesday, February 20, 2008

Formatting Date and time using JavaScript.

This link helps us in formatting the date and time in JavaScript.

Thursday, January 31, 2008

Generating dynamic date using Javascript.

function getRandomMaxMaturityDate() {

var myDate = new Date();
myDate.setDate(myDate.getDate()* (Math.random()* 555));
var date = myDate.getDay();
var month = myDate.getMonth();
var year = myDate.getYear();

document.forms[0].maxMaturityDateString.value = (month + "/" + date + "/" + year);
}

Setting parent window textbox based on pop-up window table row selection

Requirement:
I am having a parent window with a textbox and an adjacent search button. On click of the search button, a pop-up window should open with a table with 5 columns populated with rows in it and a OK button. On click of one of those rows and clicking OK button the selected row’s second column value should come and site in the parent windows text box.

JSP Code of parent page:

<td class="rmt-readOnlyRowHead" align="left" valign="top">
<span>
<html:text name="RequestForm" property="bankName" size="20" styleClass="rmt-formTxt" />
</span>
<span>
<input type="button" class="secondaryButton" id="search" value="Search"
onclick="window.open('searchBankName.do','searchBankName','resizable=1,width=710,height=650,status=1,scrollbars=1');" />
</span>
</td>

JSP Code of pop-up window:

<table id="t32bot" cellpadding="0" cellspacing="0" width="100%" border="0" id="sync">
<tbody>
<logic:iterate id="row" name="BankForm" property="bankList">
<tr id="srch_r1" clickable="yes">
<td nowrap class="rmt-tableCellTxt" onClick="clicked('t32bot',this);"> <bean:write name="row" property='countryName'/>
</td>
<td nowrap class="rmt-tableCellTxt" onClick="clicked('t32bot',this);"> <bean:write name="row" property='bankName'/>
</td>
<td nowrap class="rmt-tableCellTxt" onClick="clicked('t32bot',this);"> <bean:write name="row" property='facilityType'/>
</td>
</tr>
</logic:iterate>
</tbody>
</table>

<input type="button" class="primaryButton" id="ok" onClick="setBankName('t32bot');" value="Ok"/>

JS Code of pop-up window:

function setBankName(TABLE_NAME)
{
var bankName = window.opener.document.getElementById("bankName");
var tbl = document.getElementById(TABLE_NAME);

for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
if (tbl.tBodies[0].rows[i].className.indexOf("rmt-rowClick") != -1) {
var rowElem = tbl.tBodies[0].rows[i];
var cell = rowElem.getElementsByTagName("td")[1];
bankName.value = cell.childNodes[0].data;
window.close();
}
}
}

Tuesday, January 29, 2008

JS code to select multiple rows from a table

JSP Page

<table id="t20bot" class="grid" width="100%">
<td width="60" onClick="clicked('t20bot',this);" ><bean:write name="row" property='countryName'/></td>

JS Function

function commonClicked(table_name, elem)
{
var rowElem = elem.parentNode;
if(rowElem.className == "rmt-rowClick" )
{
rowElem.className = "";
rowElem.oldClassName = "";
}
else
{
rowElem.className = "rmt-rowClick";
rowElem.oldClassName ="rmt-rowClick";
}
}

Friday, December 28, 2007

How to close a pop-up window automatically after 5 seconds through JS

setTimeout('self.close()',500);

Tutorial one and two on setTimeout.

This link and this explains clearly about the functionality.

Monday, December 17, 2007

Disabling a button using JS

function disableButton (button1,button2)
{

document.getElementById(button1).disabled=true;
document.getElementById(button2).disabled=false;


document.forms[0].button1.readonly=true;
document.forms[0].button1.disabled=true;

}

Wednesday, December 12, 2007

To get the desired message as pop-up

To get a desired message as pop-up like

1. "Do you want to save?" with a YES/NO button
2. "Do you want to submit?" with a YES/NO button

we cannot achieve the same using Javascript. We can achieve using VB script (confirm.vbs).

Function vbMsg(isTxt,isCaption)
testVal = MsgBox(isTxt,4,isCaption)
isChoice = testVal
End Function

Here is the invoking js (confirm.js).

Here title/caption is nothing but the page heading.

var isChoice = 0;
function callAlert(Msg,Title){
txt = Msg;
caption = Title;
vbMsg(txt,caption)
if(isChoice==6){
return true;
}
return false;
}

Finally here is how we invoke it

function approveRequest(approvMsg,confirmMsg){
var confirm=callAlert(approvMsg, confirmMsg);

if(confirm) {
document.forms[0].action='abcApprove.do';
document.forms[0].submit();
}
}

JSP Page


<script type="text/javascript" src="../js/confirm.js" />
<script type="text/VBScript" src="../vbs/confirm.vbs" />

<input type="button" value="<bean:message key="request.btn.approve" bundle="gtem"/>"
onClick="approveRequest('<bean:message key="request.message.approveMessage" bundle="abc"/>','<bean:message key="common.message.confirmMessage" bundle="abc"/>');">


Application Resource Bundle:

common.message.confirmMessage = Do you really want to approve request?
request.message.approveMessage = Confirm

Saturday, November 17, 2007

Saturday, November 10, 2007

Drop-down selection using java script

We have a search criteria drop-down and a textbox to enter the value. When user selects a value from the drop-down, JS will request the user to enter a value in the textbox.


JSP Page

<html:select size="1" property="searchCriteria" name="RequestForm" styleClass="rmt-formTxt" style="margin-right:6px;">
<html:option value="">Search Criteria</html:option>
<logic:present name="RequestForm" property="searchDropList">
<bean:define id="row" name="RequestForm" property="searchDropList" />
<html:options collection="row" property="code" labelProperty="display" />
</logic:present>
</html:select>

<html:text name="RequestForm" size="30" property="searchCriteriaText" style="margin-right:6px;" styleClass="rmt-formTxt" />
<input type="button" id="search" value="<bean:message key="common.btn.search" bundle="abc"/>" class="primaryButton" onClick="normalSearch();" />
<input type="button" id="" value="<bean:message key="common.btn.clearSearch" bundle="abc"/>" class="secondaryButton" onClick="clearNormalSearch();" />

In this JS code we are getting the value(number) of the drop-down and the corresponding text.

JS Function

Explanation:

searchType is a form property with which we set the search type, whether it is a normal search (or) advanced search.

function normalSearch()
{
var searchCriteria=document.forms[0].searchCriteria.value;
var searchCriteriaValue=document.forms[0].searchCriteriaText.value;
var index;
index = document.forms[0].searchCriteria.selectedIndex;
var display = document.forms[0].searchCriteria.options[index].text
if ((searchCriteria == "") (searchCriteria == null))
{
alert("Please select a criteria for search");
document.forms[0].searchCriteria.focus();
return;
}

else if ((searchCriteriaValue == "") (searchCriteriaValue == null))
{
alert("Please enter some value for "+display);
document.forms[0].searchCriteriaText.focus();
return;
}
else
{
var searchType = document.forms[0].searchType;
searchType.value='normal';
document.forms[0].action='viewRequestResults.do';
document.forms[0].submit();
}
}

function clearNormalSearch() {
document.forms[0].searchCriteria.value = "";
document.forms[0].searchCriteriaText.value = "";
}

Tuesday, November 6, 2007

Parent-Pop-up Window - Passing parameter using JS

We have a parent page which has a textbox and button. On click of the button we open a pop-up window(Also known as picklist window) which has a single column table with values. We can select one of the values.

The requirement is that the selected value should come and sit in the parent page textbox.

Elaborating the requirement the values in the single column table will change based on the parent window(There are 3 parent windows from which this picklist pop-up window will be invoked). Means for each parent window the pop-up window table values are different.
In the database we have one table that holds all the values for all 3 different parent windows.

Solution:

We pass the pickcode and the parent window textbox property to the pop-up window action class.

Fetching the single column pop-up window values:

In the action class based on the pickcode from respective parent window we fetch the details from database and use it to iterate and display the values in the single column table in the pop-up window.

Setting in the parent window

We use pop-up windows JS to set the selected value in the single column to the parent windows textbox.

Example - PopupWindow (table)

PickID PickCode PickValues
1 QQQ ab
2 QQQ bc
3 QQQ cd
4 QQQ de
5 RRR ef
6 RRR fg
7 RRR gh
8 RRR hi
9 LLL ij
10 LLL jk
11 LLL kl
12 LLL lm

Parent window code

JSP:
<html:text name="MyForm" property="remarksToMe" />
<html:button property="contactPopup" onClick="selectFromPickList('remarksToMe','QQQ');" value=" ? "></html:button>


Javascript:


pickFlag points to the parent windows textbox property.

function selectFromPickList(pickFlag, pickCode) {

This is how we invoke a pop-up window.

window.open('searchPickList.do?pickCode='+pickCode+'&pickFlag='+pickFlag,'searchPickList','resizable=1,width=200,height=110,status=1,scrollbars=1');
}

Pop-up window code:

The keyword 'this' always refers to the current element in JS perespective.

JSP Code:

<logic:present name="PickForm" property="pickList">
<logic:iterate id="row" name="PickForm" property="pickList">

<-- <%=request.getParameter("pickFlag") % > -->
<tr id="srch_r" clickable="yes" ondblclick="pickListValue(this,
'${param.pickFlag}' );" >
<td id="picklistvalue"><bean:write name="row" property="display"/></td>
</tr>
</logic:iterate>
</logic:present>


JS Code:

function pickListValue(ROWELEM, openerFieldName)
{
var openerField = window.opener.document.all(openerFieldName);
var pickListvalue = ROWELEM.childNodes[0].childNodes[0].data;
openerField.value = pickListvalue;
window.close();
}

document.all ==> Refers to all the forms in a given JSP Page. It can have more than one form in a page.

ROWELEM.childNodes[0].childNodes[0].data;

The above line helps us to get to the data displayed using the display property.

openerFieldName gives the parent windows textbox property name, remarksToMe.

Tutorial link - 1

Sunday, November 4, 2007

Utlity Lessons

To see the parent window property's(bankName) - value from pop-up window's Javascript

alert("Result - 1: " + window.opener.document.getElementById("bankName").value);
alert("Result - 2: " + window.opener.document.forms[0].bankName.value);

<tr id="srch_r1" clickable="yes">
To align to right in a row we use colspan
<td align="left" valign="bottom" colspan="2">

We use div tag to control the entire layout/table
<div id="t1Div" style="position:relative;margin-top:5px;overflow:auto;height:95px;" type="credSummaryInfo" default="1">

<table>
---
---
</table>

margin-top:5px; ==> Is to get 5 pixel space between the previous table and this table.

http://www.richinstyle.com/test/dynamic/overflowscroll.html
overflow:scroll; ==> Is to get scrollbar(Both vertical and horizontal) for this table.
overflow:auto; ==> Is to get scrollbar(Only horizontal) for this table which is automatically created based on table size.

How to send data from a JSP page to a java class through javascript function?

<html:button property="secrecyComplianceFlag" onClick="selectFromPickList('abc','ijk');" value=" ? ">
</html:button>

function selectFromPickList(pickFlag, pickCode) {
window.open('searchPickList.do?
pickCode='+pickCode+'&pickFlag='+pickFlag+'
,'searchPickList','resizable=1,width=200,height=110,status=1,scrollbars=1');
}

The above code invokes a pop-up window, which is a JSP Page.

In the pop-window Action Class:

String code = request.getParameter("pickCode");