Friday, December 28, 2007
How to close a pop-up window automatically after 5 seconds through JS
Tutorial one and two on setTimeout.
This link and this explains clearly about the functionality.
Monday, December 17, 2007
Disabling a button using JS
{
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
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
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
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
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>
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");
To refresh parent window from pop-up window
if (window.opener.progressWindow) {
window.opener.progressWindow.close()
}
window.close();
How to refer to parent window form properties from pop-up window JS?
approvedCountIDC = window.opener.document.getElementById("approvedCountIDC");
How to set parent window form properties from pop-up window JS?
window.opener.document.getElementById("approvedCountIDC").value = 'abc';
Thursday, October 4, 2007
Adding commas and Removing commas to represent US format
Tutorial Link-2
// This function formats numbers by adding commas
function addCommas() {
var nStr = document.forms[0].requestAmount.value;
alert("Amount: " + nStr);
var prefix = '$' '';
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + ',' + '$2');
alert("Result: " + (prefix + x1 + x2));
document.forms[0].requestAmount.value = (prefix + x1 + x2);
alert("Final Request Amount: " + document.forms[0].requestAmount.value);
}
// This function formats numbers by removing commas
function removeCommas() {
// alert("inputvalue: " + document.forms[0].requestAmount.value);
var StartNumber = document.forms[0].requestAmount.value;
var TempNumber = StartNumber.replace(/\,/g,'');
var ReplacedNumber = TempNumber.replace(/\$/,'');
document.forms[0].requestAmount.value = ReplacedNumber;
// alert("Result: " + document.forms[0].requestAmount.value);
}
Tutorial on replace function.
Tuesday, August 7, 2007
Indexed properties and Highlighting a row in a table on click of it
http://faq.javaranch.com/java/IndexedProperties
Problem Description:
We have a table with 4 columns
comment (description – text box)
commenttype (drop-down)
user name (plain text – bean:write)
date (plain text – bean:write)
This is how the table looks
Comment CommentType UserName Date
textbox Drop-down Plain text Plain text
From the search screen, when user clicks NEW Request, we take him to the new screen (MyRequest.jsp) where user will see the above table as specified. But when user comes via VIEW รจ EDIT (same page - MyRequest.jsp) mode then he should see everything (all the 4 columns) as plain text (technically – bean:write tags) and not as textbox and drop-downs.
Also user should be able to add multiple rows to the table and save it to the database. User should be able to select a row (highlight a row) and delete it. Also deleted rows should not be displayed on screen.
Here we had implemented indexed properties, one of the features in struts with which we can add more than one row to a table on JSP Page and send it to java layer.
Implementation Details:
The table has an ADD button and a DELETE button at top right corner. When user clicks the ADD button an action class is invoked where we set the mandatory attributes like
1. Description (comment)
2. CommentType
3. user name
4. date
5. systemstatuskey
6. sequencenumber
7. CommentTypeKey (Associated with comment type selected)
These are the six fields in comment table in database. First 4 fields are directly related to user input from UI. Systemstatuskey field is used to identify whether the record is active (1) or deleted (3). All records are active by default. Sequence number is unique for every row that’s added to the table.
Action class:
public class AddRequestCommentAction extends DispatchAction{
public ActionForward addRequestComments(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try{
List<CommentsBean> requestCommentList = objRequestForm.getRequestCommentList();
CommentsBean objCommentsBean = new CommentsBean();
if(requestCommentList == null ) {
requestCommentList = new ArrayList<CommentsBean>();
}
objCommentsBean.setSequenceNumber(-1-requestCommentList.size());
objCommentsBean.setDescription(ABCApplicationConstants.COMMON_EMPTYSTRING);
objCommentsBean.setCommentType(ABCApplicationConstants.COMMON_EMPTYSTRING);
objCommentsBean.setCreationUserId(gtemUser.getUserId());
objCommentsBean.setCreationDate(DateUtility.todaysDate());
objCommentsBean.setSystemStatusKey(Integer.parseInt(ABCApplicationConstants.GTEMCONSTANTS_GTEMSTATUS_ACTIVE));
requestCommentList.add(objCommentsBean);
objRequestForm.setRequestCommentList(requestCommentList);
}
catch (Exception ex) {
Logger.Log(this.getClass(), "In execute->>>Exception:"+ex.getMessage(), Logger.ERROR);
}
return mapping.findForward(ApplicationConstants.CONSTANTS_SUCCESS);
}
Description:
objCommentsBean.setSequenceNumber(-1-requestCommentList.size());
The above line might have left you to wonder about negative values getting stored in DB. Actually it’s just for UI purpose. When the main SUBMIT happens in DAO layer we will be getting the count of sequencenumber from request table and adding one to it before we save it.
The way we display the rows differs from NEW mode to VIEW ==> EDIT mode.
All the 4 columns should be displayed as plain text (bean:write) for VIEW ==> EDIT mode and for NEW mode we need to show textbox, drop-down and plain texts (bean:write).
We use ‘sequence number’ property to control this requirement. As we can see in the action class we set sequencenumber with negative value, which means for a new request, when we add request comments the sequence number gets incremented in negative range. In JSP we use logic:greaterThan & logic:lessThan tags to control the way we display the rows.
We have a requirement to delete the rows. So when we delete a particular row (In both the modes) we invoke a JS where we change the SystemStatusKey to 3 to indicate it is deleted and hide the row from table on screen.
Next time when we fetch the rows from database the deleted row’s (record) systemstatuskey will be 3 indicating it’s deleted. Such deleted row shouldn’t be shown to the user.
We control it in JSP using logic:equal and logic:notEqual tags.
RequestForm:
For indexing to work we need to modify getRequestCommentBean in the below way.
public CommentsBean getRequestCommentBean(int index) {
if(this.getRequestCommentList() == null ) {
this.requestCommentList = new ArrayList<CommentsBean>();
}
while(index >= this.requestCommentList.size())
{
this.requestCommentList.add(new CommentsBean());
}
return (CommentsBean) requestCommentList.get(index);
}
MyRequest.jsp
We use the style attribute in <tr> tag to control the displaying of the row on screen.
We need to index those properties that we need to persist. Like we need to retain the value of systemstatuskey. So we include it in hidden variable and used the attribute indexed="true"
<!-- start Request Comments -->
<table id="tblComment" class="tableElem" style="position:relative;margin-top:5px;" cellspacing="0" cellpadding="2" width="100%" minmax="true" default="0">
<caption class="chrome"><span style="position:relative;float:left;"><bean:message key="request.label.commentstoABC" bundle="abc"/></span> <span
style="position:relative;float:right;"><img id="minmax2" src="../images/chrome_minimize.gif" hide="yes"></span></caption>
<thead>
<tr>
<td id="deleteComment" class="rmt-toolbar" align="right" colspan="4">
<a href="#p" id="delete" class="actionButtonUp" onclick="deleteSelectedRow('CommentTable');">
<bean:message key="common.btn.Delete" bundle="abc"/>
</a>
<a href="#P" class="actionButtonUp" id="addComment" onclick="document.forms[0].action='addRequestComment.do?method=addRequestComments';document.forms[0].submit();"/>
<bean:message key="common.btn.add" bundle="abc"/>
</a>
</td>
</tr>
<tr>
<th width="55%"><bean:message key="common.label.comment" bundle="abc"/></th>
<th width="15%"><bean:message key="common.label.commentType" bundle="abc"/></th>
<th width="20%"><bean:message key="common.label.user" bundle="abc"/></th>
<th width="10%"><bean:message key="common.label.date" bundle="abc"/></th>
</tr>
</thead>
<table id="CommentTable" class="tableElem" cellspacing="0" cellpadding="2" width="100%">
<tbody>
<logic:present name="RequestForm" property="requestCommentList">
<logic:iterate id="requestCommentBean" name="RequestForm" property="requestCommentList">
<logic:greaterThan name="requestCommentBean" property="sequenceNumber" value="0">
<logic:notEqual name="requestCommentBean" property="systemStatusKey" value="3">
<tr id="srch_r1" clickable="yes" style="display:visible" >
<!--
In this case all the values are displayed as plain text, since this is an EDIT ==> VIEW mode
-->
<!-- systemstatuskey should be the first element, as we are setting the systemstatuskey to 3 on delete, refer request.js.deleteSelectedRow(); -->
<html:hidden name="requestCommentBean" property="systemStatusKey" indexed="true" />
<html:hidden name="requestCommentBean" property="commentTypeKey" indexed="true" />
<td onClick="clicked('CommentTable',this);" width="55%">
<bean:write name="requestCommentBean" property="description" />
</td>
<td onClick="clicked('CommentTable',this);" width="15%">
<bean:write name="requestCommentBean" property="commentType" />
</td>
<td onClick="clicked('CommentTable',this);" width="20%">
<bean:write name="requestCommentBean" property="creationUserId" />
</td>
<td onClick="clicked('CommentTable',this);" width="10%">
<bean:write name="requestCommentBean" property="creationDate" />
</td>
</tr>
</logic:notEqual>
<logic:equal name="requestCommentBean" property="systemStatusKey" value="3">
<tr id="srch_r1" clickable="yes" style="display:none" >
<!-- systemstatuskey should be the first element, as we are setting the systemstatuskey to 3 on delete, refer request.js.deleteSelectedRow(); -->
<html:hidden name="requestCommentBean" property="systemStatusKey" indexed="true" />
<html:hidden name="requestCommentBean" property="commentTypeKey" indexed="true" />
</tr>
</logic:equal>
</logic:greaterThan>
<logic:lessThan name="requestCommentBean" property="sequenceNumber" value="0">
<logic:notEqual name="requestCommentBean" property="systemStatusKey" value="3">
<tr id="comm_r7" clickable="yes" style="display:visible" >
<!-- systemstatuskey should be the first element, as we are setting the systemstatuskey to 3 on delete, refer request.js.deleteSelectedRow(); -->
<html:hidden name="requestCommentBean" property="systemStatusKey" indexed="true" />
<td width="55%" onClick="clicked('CommentTable',this);" >
<html:textarea rows="3" cols="1" name="requestCommentBean" indexed="true" size="120" property="description" maxlength="2047" style="margin-right:6px;" styleClass="rmt-formTxt" />
</td>
<td width="15%" onClick="clicked('CommentTable',this);" >
<html:select size="1" property="commentTypeKey" name="requestCommentBean" indexed="true" styleClass="rmt-formTxt" style="margin-right:6px;" >
<html:option value="">Comment Type</html:option>
<logic:present name="RequestForm" property="lstRequestCommentTypes">
<bean:define id="row" name="RequestForm" property="lstRequestCommentTypes" />
<html:options collection="row" property="key" labelProperty="display"/>
</logic:present>
</html:select>
</td>
<td onClick="clicked('CommentTable',this);" width="20%">
<bean:write name="requestCommentBean" property="userName"/>
</td>
<td onClick="clicked('CommentTable',this);" width="10%">
<bean:write name="requestCommentBean" property="creationDate" />
</td>
</tr>
</logic:notEqual>
<logic:equal name="requestCommentBean" property="systemStatusKey" value="3">
<tr id="comm_r7" clickable="yes" style="display:none" >
<!-- systemstatuskey should be the first element, as we are setting the systemstatuskey to 3 on delete, refer request.js.deleteSelectedRow(); -->
<html:hidden name="requestCommentBean" property="systemStatusKey" indexed="true" />
<html:hidden name="requestCommentBean" property="commentTypeKey" indexed="true" />
</tr>
</logic:equal>
</logic:lessThan>
</logic:iterate>
</logic:present>
</tbody>
</table>
</table>
<!-- end of RequestComments -->
When one of the rows is clicked, we need to highlight that row. Here is the JS code for it.
function clicked(table_name, elem )
{
var rowElem = elem.parentNode;
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)
{
tbl.tBodies[0].rows[i].className="";
}
}
rowElem.className = "rmt-rowClick";
}
Here is the JS code to delete the row from UI and set systemStatusKey value to 3.
//This function deletes the row and changes systemstatuskey to 3
// Note: keep systemstatuskey as first element of the row.
function deleteSelectedRow(TABLE_NAME)
{
hasLoaded=true;
if (hasLoaded) {
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 elem=rowElem.getElementsByTagName("input")[0];
elem.value=3;
tbl.tBodies[0].rows[i].style.display='none';
break;
}
}
}
}