Archive

Posts Tagged ‘Javascript’

How To Create A Calendar Using An HTML Table And JavaScript

December 3rd, 2009 No comments

Assuming you’d need to create a calendar (or 2) in order to add in some text for specific dates, you’d probably want to create your own calendar using a simple HTML table and few lines of Javascript and later (depending on what additional text you want to display), you could add in some jQuery code to access the cells for the specific dates and modify their contents.

1
2
3
4
//Some constants
var monthLabels = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var daysOfWeek = new Array("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

The function below, takes the following parameters:
monthId = 1 or 2, month = 0 to 11, year = 2009 and above

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function constructCalendarTable(monthId,month,year)
{ var dateObj = new Date(); dateObj.setDate(1); dateObj.setMonth(month); dateObj.setYear(year);
  var dow_theFirstOfMonth = dateObj.getDay();
 
  //Get the maximum number of days in current month
  var maxDaysIntheMonth = daysInMonth[month];
  if(month == 1) { if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){ maxDaysIntheMonth = 29; } }
 
  //Creating the table
  var calmonthtd = $("#calmonth"+monthId+"td");
  var caltable = $("<table>").attr("align","center"); caltable.appendTo(calmonthtd);
 
  //Creating the label row
  var rowRMonthLabel = $("<tr>").attr("align","center"); rowRMonthLabel.appendTo(caltable);
  var rowRMonthLabelCell = $("<td>").attr("colspan","7").text(monthLabels[month]+", "+year);
  rowRMonthLabelCell.appendTo(rowRMonthLabel);
 
  //Creating the rest of the rows
  var rowR = $("<tr>"); rowR.appendTo(caltable);
 
  var dayOfMonthCounter = 0;
  for (var i=1;i<50;i++)
  { if(i%7==1) { rowR = $("<tr>"); rowR.appendTo(caltable); }
    var cellR = $("<td>").attr("id","calmonth"+monthId+"d"+i);
    if(i<=7) 
    { //Populating the days' headers
      cellR.addClass("calhdr").text(daysOfWeek[i-1]);
    }
    else 
    { //Populating the days
      var dayOfWeek = (i%7);
      if(dayOfWeek==dow_theFirstOfMonth && dayOfMonthCounter==0) {  dayOfMonthCounter=1; cellR.text(dayOfMonthCounter).addClass("calday"); }
      else if(i<=49 && dayOfMonthCounter>=1 && dayOfMonthCounter<maxDaysIntheMonth) { dayOfMonthCounter++; cellR.text(dayOfMonthCounter).addClass("calday"); }
      else
      cellR.text("").addClass("calnonday");
    }
    cellR.appendTo(rowR);
  }
}

[Update Dec 9, 2009]
I have used this code in one of my pet projects, http://cheapflightsearch.appspot.com/

Categories: Javascript Tags: , ,

Saving Ordering Of A Sortable List Using jQuery UI

July 21st, 2009 No comments

I have a list of items (for brevity, lets call them item1, item2, item3 and item4) which are retrieved from the backend and displayed on a list of sorts.

I wanted to allow the user to update the ordering of these items and that action would automatically update the backend each time there was a change made to the order. So, what I wanted the backend to receive was a comma separated list of IDs of the new sequence/order of the items, similar to

3,2,1,4

Here’s a snippet of the required HTML

<ul id="mylist">
   <li id="myItem_1"><img src="icon.png" title="Drag Me" />Item 1</li>
   <li id="myItem_2"><img src="icon.png" title="Drag Me" />Item 2</li>
   <li id="myItem_3"><img src="icon.png" title="Drag Me" />Item 3</li>
   <li id="myItem_4"><img src="icon.png" title="Drag Me" />Item 4</li>
</ul>

You will notice that the items have an id with prefix myItem_ followed by the actual numeric ID assigned to those items (by the backend).

Here’s the supporting javascript code using jQuery UI’s sortable feature.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$(document).ready(function() {
  $("#mylist").sortable({
  handle : '.handle',
  update : function () {
    var newOrdering = $('#mylist').sortable('toArray');
    var l = "myItem_".length;
    var newOrderIds = new Array(newOrdering.length);
    var ctr = 0;
    // Loop over each value in the array and get the ID
    $.each(
      newOrdering,
      function(intIndex, objValue) {
        //Get the ID of the reordered items 
        //- this is sent back to server to save
        newOrderIds[ctr] = objValue.substring(l,objValue.length);
        ctr = ctr + 1;
      }
    );
    alert("newOrderIds : "+newOrderIds); //Remove after testing
    $("#info").load("save-item-ordering.jsp?"+newOrderIds);
  }
  });
});

Notice line 15

15
        newOrderIds[ctr] = objValue.substring(l,objValue.length);

The objValue looks like myItem_1, where 1 is the ID assigned to an item by the backend. This is why the the ID is being extracted out by the above line of code.

Credits:

Categories: Javascript Tags: ,

Dynamically Creating HTML Tables, Rows And Cells

July 20th, 2009 No comments

Requires only a placeholder table, under which new rows and cells will be added later

<table id="myTable1">
  <tbody>
  </tbody>
</table>

To add a row to this table

  var rowX = $("<tr>"); rowX.appendTo(tableToAddTo);

To add a cell at a specific index in this row

1
2
3
4
5
6
7
8
  function createTableRowCell(rowToAddTo, columnIndex, idToAssign, cellContents, cellClass)  {
  $("<td>")
    .addClass(cellClass)
    .text(cellContents)
    .data("col", columnIndex)
    .attr("id",idToAssign)
    .appendTo(rowToAddTo);
}

Example, here a row is being added to the table “myTable1″ and then a cell is being added to the recently-added row at index 0.

  var tableToAddTo = $("#myTable1");
  var rowX = $("<tr>"); rowX.appendTo(tableToAddTo);
  var cellY = createTableRowCell(rowX, 0, taskId, taskTitle, "someClassTBD");
Categories: Javascript Tags: ,

Getting Dates For A Particular Day Of The Week In Upcoming X Weeks

July 12th, 2009 No comments

A modification of a simple Javscript function used to get the dates for a particular day of the week in the upcoming X weeks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<script language="javascript">
<!--//
var todaysDate = new Date();
var startDate = todaysDate, endDate = startDate;
function getDayXOfWeekArray(dayXOfWeek,numWeeks) 
{ var dayXOfWeekArray = new Array();
  var d = new Date();
  startDate = d;
  //Updating the endDate based on the number of weeks we want the dates for
  endDate.setTime(todaysDate.getTime() + (86400000*7*numWeeks));
  endDateDay = endDate.getDate();
  //Getting the dates
  var startDateTime = startDate.getTime();
  var endDateTime = endDate.getTime();
  var loopDate = new Date();
  var dow, index=0;
  for (var i=startDateTime;i<=endDateTime;i+=86400000) 
  { loopDate.setTime(i);
     dow = loopDate.getDay();
     if (dow == dayXOfWeek) 
    { //Storing the date
      //NOTE: I use formatDate() function from http://www.mattkruse.com/javascript/date/index.html
      dayXOfWeekArray[index] = formatDate(loopDate,"ddNNNyyyy");
      index++;
      i+=86400000;
    }
  }
  return dayXOfWeekArray;
}//end-of-getDayXOfWeekArray
//-->
</script>

The dayXOfWeekArray returned by the getDayXOfWeekArray function stores the dates in the ddMMMYYYY format. For example, if we want the dates of the next 10 Fridays, the parameters passed to this function would look like

var dayXOfWeekArray = getDayXOfWeekArray(5,10);

The dayXOfWeekArray would contain 10 date strings (17Jul2009, 24Jul2009, 31Jul2009, 07Aug2009, 14Aug2009, 21Aug2009, 28Aug2009, 04Sep2009, 11Sep2009 & 18Sep2009) all of which fall between today (12Jul2009) and 20Sep2009.

Using the formatDate() function from http://www.mattkruse.com/javascript/date/index.html, it is very easy to format dates. Moreover, the required Javascript file, date.js is just 6 kb in size.

Categories: Javascript Tags:

Asychronously Saving Editable Data

March 2nd, 2009 No comments

There are several very good Javascript libraries out there, but sometimes, they are just too heavy for simple jobs, like for example, editing a single cell in an otherwise static data display in a table.

I use a very small Javascript library from www.ajaxtoolbox.com, just 8.5 kb in size. It allows me to make the required AJAX calls to the backend server/script/servlet without having to write too many lines.

Elaborating on my example, (say) there’s a page dispalying data about a person, (say) the usual name, age, phone number, etc. Now, we’d like to make the td containing the phone number as editable. We would insert the following inside that td
<input type="text" name="phoneNumber" id="phoneNumber" value="12345678" onchange="return saveData();" />

The Javascript code would look like

1
2
3
4
5
6
7
function saveData() {
  AjaxRequest.get( {
 'url':'../asynchsave/itemtype=phoneNumber&value='+escape(document.getElementById('phoneNumber').value)
     ,'onSuccess': function(req){ alert(req.responseText);  }
   });  
   return false;
}// end-of-saveData
Categories: Javascript Tags:

Highlighting Colour Of Row Upon Mouse Click

January 30th, 2008 1 comment

I wanted some Javascript code that would allow me to highlight a row in a table, when the user clicked on a link or a radio button.

So, I tried out some code (below) to get the effect I wanted.

First, the required Javascript.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script type="text/javascript"><!--
var lastSelectedRow;
//Assuming that the background colour for all rows is white by default
var defaultRowBgColor = 'white';
function highlightrow(rowId) {
  //Clearing the background color of the previously highlit rows
  if(lastSelectedRow!=null)
    document.getElementById(lastSelectedRow).bgColor = defaultRowBgColor;
  //Highlighting the row specified by 'rowId'
  //Here, we highlight with yellow
  document.getElementById(rowId).bgColor = 'yellow';
  lastSelectedRow = rowId;
}
--></script>

Next, the section of the HTML code for the table, whose rows I want to highlight when the link “Click Me” is clicked.

The first row has the ID “row1″, so, calling highlightrow(‘row1′) indicates to that function to highlight only that row and reset the background colour of any previously selected row to the default colour.

The HTML code for the other rows in this table would similar to as shown below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<table>
  <tbody>
    <tr id="row1">
      <td>row 1 column 1</td>
      <td>row 1 column 2</td>
      <td><a href="" onclick="highlightrow('row1'); return false;">Click Me</a></td>
    </tr>
    <tr id="row2">
      <td>row 2 column 1</td>
      <td>row 2 column 2</td>
      <td><a href="" onclick="highlightrow('row2'); return false;">Click Me</a></td>
    </tr>
    <tr id="row3">
      <td>row 3 column 1</td>
      <td>row 3 column 2</td>
      <td><a href="" onclick="highlightrow('row3'); return false;">Click Me</a></td>
    </tr>
  </tbody>
</table>

That’s all there is to it. Hope this helps someone out there.

Categories: Javascript Tags: