Wednesday, December 24, 2008

Adding Image with Onclick to Dom Tree using Ajax Step 50

Sometimes using Ajax you will need to add the objects to the DOM tree in your jsp page.

For example, if you have an image that is a calender and you want to display it using Ajax, you will need to add it to your DOM tree.

You have to becareful about how you implement this because different browsers operate in different ways.

Here is an example of that.

In my javascript function I have a loop where x is the value from the loop:

This code creates an input text box and sets its attributes. This box will hold the data from the calender. This code works correctly.

var td5=document.createElement("input");
td5.setAttribute("type","text")
td5.setAttribute("id","candidateProject.projectDeliverables[" +x+ "].neededByAsStr");
td5.setAttribute("name","candidateProject.projectDeliverables[" +x+ "].neededByAsStr");
td5.setAttribute("size","11");
td5.setAttribute("value",items[x]);
td5.setAttribute("readOnly","true");
document.getElementById("deliverable"+ x).appendChild(td5);

This code will add the calender object to the DOM tree. I want the calender to work in IE and Firefox and this code here only works in IE.

var newString="<img onclick="'displayCalendarDeliverable(this," height="'20'" alt="'Calendar'" src="resources/images/cal.gif" width="'20'" />";
td5=document.createElement(newString);
document.getElementById("deliverable"+ x).appendChild(td5);


The correct way would be to create an object like this:

var image = document.createElement("img");
image.setAttribute("alt","Calendar")
image.setAttribute("width",20)
image.setAttribute("height",20)
image.id="image"+ x
image.src ='resources/images/cal.gif';
document.getElementById("deliverable"+ x).appendChild(image);

This last bit of code is to be used to create the onclick functionality. However, this code works if the X wasn't a variable, but it is a variable, so it doesn't work.

document.getElementById("image"+x).onclick=function(){displayCalendarDeliverable(this,x);}

There are a few different ways to do this:

document.getElementById("image" +x).onclick=Function("displayCalendarDeliverable(this," +x+ ")"); }

or

document.getElementById("image" +x).onclick=function(){displayCalendarDeliverable(this, Number(this.id.substr(5))); }



Ajax SweetDev Tutorial for More Ajax
Go To Step 51

0 comments: