Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, July 28, 2008

Adding options to optgroup tag dynamically/programmatically

Inorder to add options to an optgroup tag dynamically, we need to
1) assign an id to the optgroup say id="firstgrpid"
2) add an attribute to each of the option tags say "parentid" having a value same as the optgroup id (as mentioned in step 1)
thats all that needs to be done....!!!

when moving elements from left-to-right what needs to be done for each option tag that has been selected from the source list(left hand side list) is
1) create an option tag as shown below with the selected option tags text and value

var optnew = new Option(currentNode.text, currentNode.value, false);

2)use the setAttribute() to set the "parentid" attribute for the new option tag.
3) add the new option to the destination list tag.

destArray.options[len] = optnew ;


When moving option tags from right-to-left we need to do the above 3 steps and
4) get the value of the "parentid" attribute which contains the parent to which we need to attach the new option tag
5) add the new option tag based on the value of "parentid" attribute.

//get the parent id and add the element to it
tempEle = document.getElementById(tempEleId);
tempEle.appendChild(optnew);
// the below lines of codes are needed for IE otherwise the elements is not displayed in the browser.
optnew.value = currentNode.value;
optnew.text = currentNode.text;


when moving elements up or down, we need to
1) get an index of the current selected option
2) if moving up then increase that index (step 1) by 1 or if moving down then decrease that index (step 1) by 1
3)create 2 new option tags and set the "parentid" attribute.
4) interchange the 2 option tags.

//used to interchange the element positions when moving up and down
function swapOptions(obj,i,j)
{

var i_selected ;
var j_selected ;



i_selected = obj[i].selected;
j_selected = obj[j].selected;

//1st element to swap
var temp = new Option(obj[i].text, obj[i].value, obj[i].defaultSelected, obj[i].selected);
var currentNode = obj.options[i];
for(var l = 0; l < currentNode.attributes.length; l++)
{
if(currentNode.attributes[l].nodeName == "parentid")
{
temp.setAttribute(currentNode.attributes[l].nodeName,currentNode.attributes[l].nodeValue);
}
}

var temp2= new Option(obj[j].text, obj[j].value, obj[j].defaultSelected, obj[j].selected);
var currentNode = obj.options[j];
for(var l = 0; l < currentNode.attributes.length; l++)
{
if(currentNode.attributes[l].nodeName == "parentid" )
{
temp2.setAttribute(currentNode.attributes[l].nodeName,currentNode.attributes[l].nodeValue); }
}

obj[i] = temp2;
obj[j] = temp;
obj[i].selected = j_selected;
obj[j].selected = i_selected;

}





full source code

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<script type="text/javascript">

//add elements from source to destination and vice-versa
function moveleftright(isAdd)
{
if (isAdd)
{
//source to destination (left to right)
destArray = document.getElementById('destArray');
sourceArray = document.getElementById('sourceArray');
}
else
{
//destination to source (right to left)
sourceArray = document.getElementById('destArray');
destArray = document.getElementById('sourceArray');
}

var myArray=new Array();
var tempCount=0;
var len = destArray.length;
var orgLen = sourceArray.length;

// get a list of all selected elements
for(var i = 0; i < orgLen; i++)
{
if ((sourceArray.options[i] != null) && (sourceArray.options[i].selected))
{
var currentNode = sourceArray.options[i];
var optnew = new Option(currentNode.text, currentNode.value, false);
var tempEleId = "";

for(var j = 0; j < currentNode.attributes.length; j++)
{
if(currentNode.attributes[j].nodeName == "parentid" )
{
optnew.setAttribute(currentNode.attributes[j].nodeName,currentNode.attributes[j].nodeValue);
//store the parent's id in 'tempEleId' so that while removing elements they will be added back to parent.
if(!isAdd && currentNode.attributes[j].nodeName == "parentid")
{
tempEleId = currentNode.attributes[j].nodeValue;
}
}
}
if (isAdd)
{
//add elements at the end
destArray.options[len] = optnew ;
}
else
{
if(tempEleId && tempEleId.length > 0)
{

//get the parent id and add the element to it
tempEle = document.getElementById(tempEleId);
tempEle.appendChild(optnew);
// the below lines of codes are needed for IE otherwise the elements is not displayed in the browser.
optnew.value = currentNode.value;
optnew.text = currentNode.text;

}
}

myArray[tempCount] = currentNode.text;
tempCount++;
len++;
}
}

//Remove the values in from the source list
for (var j=0; j<myArray.length; j++)
{
for (var n=0; n<sourceArray.length; n++)
{

if (myArray[j] == sourceArray.options[n].text && sourceArray.options[n].selected)
{

sourceArray.options[n] = null;

}
}
}


}

//used to interchange the element positions when moving up and down
function swapOptions(obj,i,j)
{

var i_selected ;
var j_selected ;



i_selected = obj[i].selected;
j_selected = obj[j].selected;

//1st element to swap
var temp = new Option(obj[i].text, obj[i].value, obj[i].defaultSelected, obj[i].selected);
var currentNode = obj.options[i];
for(var l = 0; l < currentNode.attributes.length; l++)
{
if(currentNode.attributes[l].nodeName == "parentid")
{
temp.setAttribute(currentNode.attributes[l].nodeName,currentNode.attributes[l].nodeValue);
}
}

var temp2= new Option(obj[j].text, obj[j].value, obj[j].defaultSelected, obj[j].selected);
var currentNode = obj.options[j];
for(var l = 0; l < currentNode.attributes.length; l++)
{
if(currentNode.attributes[l].nodeName == "parentid" )
{
temp2.setAttribute(currentNode.attributes[l].nodeName,currentNode.attributes[l].nodeValue); }
}

obj[i] = temp2;
obj[j] = temp;
obj[i].selected = j_selected;
obj[j].selected = i_selected;

}






/* Move selected option in a select list up one*/
function moveOptionUp(argThis)
{
destArray = document.getElementById('destArray');

for (i=0; i<destArray.options.length; i++)
{
if (destArray.options[i].selected)
{
if (i != 0 && !destArray.options[i-1].selected)
{
swapOptions(destArray,i,i-1);
}
}
}
}

/* Move selected option in a select list down one*/
function moveOptionDown(argThis)
{
destArray = document.getElementById('destArray');

for (i=destArray.options.length-1; i>=0; i--)
{
if (destArray.options[i].selected)
{
if (i != (destArray.options.length-1) && ! destArray.options[i+1].selected)
{
swapOptions(destArray,i,i+1);
}
}
}
}

</script>

</head>
<body>
<form id="createBatchTemplate" name="createBatchTemplate" action="#" method="post">


<div style="padding-bottom:10px;">
<table cellspacing="0">
<colgroup>
<col style="width: 30%" />
<col style="width: 10%" />
<col style="width: 30%" />
<col style="width: 10%" />
</colgroup>
<tbody>
<tr align="left">
<th style="text-align:left; font-siz:60%;margin-bottom:3px"><label>
left columns
</label></th>
<td></td>
<th style="text-align:left; font-siz:60%;margin-bottom:3px"><label>
right columns
</label></th>
<td></td>
</tr>
<tr>

<td><select id="sourceArray" name="sourceArray"
multiple size=10>
<optgroup label='1st group' id="firstgrpid">
<option parentid="firstgrpid" value='grp1element1'/>grp1 element1</option>
<option parentid="firstgrpid" value='grp1element2'/>grp1 element2</option>
<option parentid="firstgrpid" value='grp1element3'/>grp1 element3</option>
<br />
</optgroup>
<optgroup/>

<optgroup label='2nd group' id="secondgrpid">
<option parentid="secondgrpid" value='grp2element1'/>grp2 element1</option>
<option parentid="secondgrpid" value='grp2element2'/>grp2 element2</option>
<br />
</optgroup>
</select></td>
<td align="center" valign="middle"><br />
<br />
<br />


<input type="button" id="addToDest"
onclick="javascript:moveleftright(true);"
value='move right'/>
<br />
<br />
<input type="button"
id="addToSrc"
onclick="javascript:moveleftright(false);"
value='move left'/>

</td>

<td><select id="destArray" name="destArray"
multiple size=10 >
</select></td>
<td align="center" valign="middle"><br />
<br />
<br />
<input type="button"
id="MoveUp"
onclick="javascript:moveOptionUp(this)"
value='move up' />
<br />
<br />
<input type="button" id="MoveDown" onclick="javascript:moveOptionDown(this);"
value='move down' /></div>
</td>
</tr>
</tbody>
</table>

</div>
</td>

</tr>

</table>

</form>

</body>
</html>

Thursday, March 6, 2008

Javascript and XPath

In IE once an xml file has been loaded we need to set a property so that XPath can be used:

xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("someFile.xml");
xmlDoc.setProperty("SelectionLanguage","XPath");

for other browsers like Firefox we need to set :

xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("someFile.xml");
var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);

before calling the evaluate() method.

'selectionsPath' is the xpath expression that we need to form and then for getting the value(s),

//Internet explorer
if (ie)
{
var actions = xmlDoc.selectNodes(selectionsPath);
var i = 0;
for (i=0;i<actions.length;i++)
{
alert(actions[i].childNodes[0].nodeValue);
}
}
else
{
//mozilla
var actions = xmlDoc.evaluate(selectionsPath, xmlDoc, nsResolver, XPathResult.ANY_TYPE,null);
var result=actions.iterateNext();

while (result)
{
alert(result.textContent);
result=actions.iterateNext();
}
}

Tuesday, March 4, 2008

Javascript calendar showing daily events

For the basic part of constructing and displaying a HTML calendar in javascript please refer to url:
http://jszen.blogspot.com/2007/03/how-to-build-simple-calendar-with.html

Making use of the above calendar , all that is needed inorder to show events on a day to day basis, is to get a list of events for a particular day. The structure for storing the events for each day can be an xml file or a json file or any other kind of data structure that is approrpiate.

what changes are needed to be made to the code at url: http://jszen.blogspot.com/2007/03/how-to-build-simple-calendar-with.html

1) in "Calendar.prototype.generateHTML" function add a function to return all the events for a particular day

html += getDayEvents(tempYear, tempMonth, day);

2) The xml file that is used in this example is shown below:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<year id="2008">
<month id="2">
<days id="1">
<events><a href="#" target="_blank"> some other event</a></events>
</days>
<days id="2">
</days>
</month>
<month id="3">
<days id="6">
<events><a href="#" target="_blank"> some other event</a></events>
</days>
<days id="2">
</days>
</month>
</year>

3) code the javascript function

function getDayEvents(year, month, day)
{
var dayevents = "&nbsp";
//months are being referred to as Jan=0. Feb=1, etc so add 1 to the month so that it matches the normal calendar months
var tempmonth = month + 1;

var rowcount=xmlDoc.getElementsByTagName('days');
var found = false;

for(ii=0; !found && ii<rowcount.length;ii++)
{
//check if we have got the correct day , month and year
if ( (rowcount[ii].getAttribute('id') == day) && (rowcount[ii].parentNode.getAttribute('id') == tempmonth)
&& (rowcount[ii].parentNode.parentNode.getAttribute('id') == year) )
{
//get a list of all events for that day
for(jj=0;jj<rowcount[ii].childNodes.length;jj++)
{
if (rowcount[ii].childNodes[jj].text != "undefined")
{
dayevents += rowcount[ii].childNodes[jj].text;
}
}
found = true;
}
}

return dayevents;
}

4) To show previous month and next month events, add the code below to "Calendar.prototype.generateHTML" function:

html += '%lt;th colspan="1" align="left" id="previousmonth">%lt;a href="javascript:previousmonth('+currentMonth+','+ currentYear+')">previous month%lt;/a>%lt;/th>';
html += '%lt;th colspan="5" align="center">' + monthName + " " + this.year ;
html += '%lt;th colspan="1" align="right">%lt;a href="javascript:nextmonth('+currentMonth+','+ currentYear+')">next month%lt;/a>%lt;/th>';

5) code the previous and next months javascript functions

function nextmonth(month, year)
{
var nextMnth = month + 1;
if(nextMnth > 11)
{
nextMnth = 0;
year = year + 1;
}
var cal = new Calendar(nextMnth,year);
cal.generateHTML();
document.getElementById('calendarID').innerHTML = cal.getHTML();
}

function previousmonth(month ,year)
{
var prevMonth = month - 1;
if(prevMonth < 0)
{
prevMonth = 11;
year = year - 1;
}
var cal = new Calendar(prevMonth,year);
cal.generateHTML();
document.getElementById('calendarID').innerHTML = cal.getHTML();
}



The complete code is below:

%lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
%lt;html lang=en xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
%lt;head>
%lt;style type="text/css">
.calendar-table{
width : 100%;
border : 1px solid black;
}

.calendar-header{

}

.calendar-header-day {
width:14% ;
align:center;
border : 1px solid green;
}

.calendar-day{
height : 100px;
padding : 2px;
border : 1px solid blue;
}
%lt;/style>
%lt;script type="text/javascript">
//credit to http://jszen.blogspot.com/2007/03/how-to-build-simple-calendar-with.html for the logic

// these are labels for the days of the week
cal_days_labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

// these are human-readable month name labels, in order
cal_months_labels = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'];

// these are the days of the week for each month, in order
cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

// this is the current date
cal_current_date = new Date();

var currentMonth;
var currentYear;
function Calendar(month, year) {
this.month = (isNaN(month) || month == null) ? cal_current_date.getMonth() : month;
this.year = (isNaN(year) || year == null) ? cal_current_date.getFullYear() : year;
this.html = '';
currentMonth=this.month;
currentYear=this.year;
}

Calendar.prototype.generateHTML = function(){
var xmlDoc;
parseXML();
// get first day of month
var firstDay = new Date(this.year, this.month, 1);
var startingDay = firstDay.getDay();

// find number of days in month
var monthLength = cal_days_in_month[this.month];

// compensate for leap year
if (this.month == 1) { // February only!
if((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0){
monthLength = 29;
}
}

// do the header
var monthName = cal_months_labels[this.month]
var html = '%lt;table class="calendar-table" cellspacing="1" cellpadding="2">';
html += '%lt;tr>';
html += '%lt;th colspan="1" align="left" id="previousmonth">%lt;a href="javascript:previousmonth('+currentMonth+','+ currentYear+')">previous month%lt;/a>%lt;/th>';
html += '%lt;th colspan="5" align="center">' + monthName + " " + this.year ;
html += '%lt;th colspan="1" align="right">%lt;a href="javascript:nextmonth('+currentMonth+','+ currentYear+')">next month%lt;/a>%lt;/th>';
html += '%lt;/th>%lt;/tr>';
html += '%lt;tr class="calendar-header">';
for(var i = 0; i %lt;= 6; i++ ){
html += '%lt;td class="calendar-header-day">';
html += cal_days_labels[i];
html += '%lt;/td>';
}
html += '%lt;/tr>%lt;tr>';


// fill in the days
var day = 1;
var tempMonth = this.month;
var tempYear = this.year ;
// this loop is for is weeks (rows)
for (var i = 0; i %lt; 9; i++) {
// this loop is for weekdays (cells)
for (var j = 0; j %lt;= 6; j++) {
html += '%lt;td class="calendar-day" valign="top">';
if (day %lt;= monthLength && (i > 0 || j >= startingDay)) {
html += day ;
html += getDayEvents(tempYear, tempMonth, day);
day++;
}
html += '%lt;/td>';
}
// stop making rows if we've run out of days
if (day > monthLength) {
break;
} else {
html += '%lt;/tr>%lt;tr>';
}
}
html += '%lt;/tr>%lt;/table>';

this.html = html;

function parseXML()
{
try
{ //try IE first
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try
{ //try Mozilla, Firefox, Opera, etc.
xmlDoc=document.implementation.createDocument("","",null);
}
catch(e)
{
alert(e.message);
return;
}
}
xmlDoc.async=false;
xmlDoc.load("CalendarEvents.xml");

}

function getDayEvents(year, month, day)
{
var dayevents = "&nbsp";
var tempmonth = month + 1;

var rowcount=xmlDoc.getElementsByTagName('days');
var found = false;

for(ii=0; !found && ii%lt;rowcount.length;ii++)
{
if ( (rowcount[ii].getAttribute('id') == day) && (rowcount[ii].parentNode.getAttribute('id') == tempmonth)
&& (rowcount[ii].parentNode.parentNode.getAttribute('id') == year) )
{
for(jj=0;jj%lt;rowcount[ii].childNodes.length;jj++)
{
if (rowcount[ii].childNodes[jj].text != "undefined")
{
dayevents += rowcount[ii].childNodes[jj].text;
}
}
found = true;
}
}

return dayevents;
}


}

Calendar.prototype.getHTML = function() {
return this.html;
}

function nextmonth(month, year)
{
var nextMnth = month + 1;
if(nextMnth > 11)
{
nextMnth = 0;
year = year + 1;
}
var cal = new Calendar(nextMnth,year);
cal.generateHTML();
document.getElementById('calendarID').innerHTML = cal.getHTML();
}

function previousmonth(month ,year)
{
var prevMonth = month - 1;
if(prevMonth %lt; 0)
{
prevMonth = 11;
year = year - 1;
}
var cal = new Calendar(prevMonth,year);
cal.generateHTML();
document.getElementById('calendarID').innerHTML = cal.getHTML();
}

function init()
{
var now = new Date();

var cal = new Calendar(now.getMonth(),now.getFullYear());
cal.generateHTML();
document.getElementById('calendarID').innerHTML = cal.getHTML();
}
%lt;/script>

%lt;/head>
%lt;body onload="init()">

%lt;div id="calendarID">%lt;/div>
%lt;/body>
%lt;/HTML>

Wednesday, February 27, 2008

Accessing javascript methods from an IFRAME

If you need to access any javascript methods defined in the parent/main webpage from an IFRAME make use of the top property followed by the javascript method name ex. top.myfunction() ; where myfunction() has been defined in the parent/main webpage.


vice-versa to access methods from within an IFRAME in the parent/main webpage, you will need the following syntax:
window.<>.<> ex.window.sub_frame.subpagedisplay(); where sub_frame is the frame ID defined in the parent/main webpage and subpagedisplay() is the javascript function defined in the subpage or in the iframe src property.



NOTE: Both the html files shown below need to be on the same DOMAIN as browsers do NOT allow cross-site scripting.

complete parent/main webpage code: mainHTML.html


<html>
<head>
</head>
<iframe id="sub_frame" name="sub_frame" src="sub_frame.html"></iframe>

<script type="text/javascript"><!--
function myfunction()
{
alert('main page function called');
}

function subpagefn()
{
window.sub_frame.subpagedisplay();
}
//-->
</script>
<body>
main page
<a href="javascript:subpagefn();">call sub page function</a>
</body>
</html>




complete subpage/IFRAME webpage code: sub_frame.html

<html>
<head>
<script type="text/javascript"><!--
function showme()
{
top.myfunction() ;
}

function subpagedisplay()
{
alert('in sub page');
}
//-->
</script>
</head>
<body>
iframe page
<a href="javascript:showme()">some link</a>
</body>
</html>

Tuesday, February 26, 2008

Creating dynamic HTML tables with Javascript

when creating a dynamic HTML table in javascript, first
1) create a TABLE
2) create a TBODY
3) create rows, TR
4) create cells, TD
5) append the cells TD to the rows TR
6) append the rows TR to the TBODY
if this is not done then the entire table will not be visible.
7) append the TBODY to the TABLE
8) attached the TABLE to the required DOM node in HTML document

complete code for the above steps:

var newTbody = document.createElement("tbody");
var mainTable = document.createElement("table");
var newTR = document.createElement("tr");
var newTD = document.createElement("td");
newTD.innerHTML = 'some text';
newTR.appendChild(newTD);
newTbody.appendChild(newTR);
mainTable.appendChild(newTbody);
document.getElementById('someDomID').appendChild(mainTable);


The following code without a TBODY ends up with the entire TABLE not being visible.

var mainTable = document.createElement("table");
var newTR = document.createElement("tr");
var newTD = document.createElement("td");
newTD.innerHTML = 'some text';
newTR.appendChild(newTD);
mainTable.appendChild(newTR);
document.getElementById('someDomID').appendChild(mainTable);