Just getting started with jQuery, and I’ve had some success so far. I’ve created a handler that updates a <table> every time a user makes a selection from a dropdown. It looks mostly like this:
function loadAttributes() {
$.ajax({
type: "POST",
url: "../ws/itemSearch/getAttributesForItemType",
contentType: 'application/xml',
data: '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.itemsearch.foo.com/">'
+ '<soapenv:Header/><soapenv:Body><ser:getAttributesForItemType>'
+ '<arg0>' + this.value + '</arg0>'
+ '</ser:getAttributesForItemType></soapenv:Body></soapenv:Envelope>',
processData: false,
dataType: "xml",
success: function(data) {
var attributes = '<table summary="Attribute Section"><tr class="underline">';
var attCount = 0;
$(data).find("return").each(
function() {
if (++attCount % 4 == 0) {
attributes += '</tr><tr class="underline">';
}
// TODO PMA click handler to the new <td> element
attributes += '<td>' + this.textContent + '</td>';
}
);
attributes += '</tr></table>';
$("div[id=attributes]").html(attributes);
}
});
}
As you can see my next step is to not just add literal <td> elements to the row containing the attributes, but to add a click handler to them. This click handler would append the contents of the <td> to a text box; something like:
tdItem.click(function() {
$("input[name=search]").append(tdItem.textContent);
}
To do that, I’d prefer to create each td item as a separate Element and build up the table in an object-oriented manner using <tr> elements rather than pasting together a literal string which is what I’m doing now. Most of the examples on the jQuery site have to do with adding listeners to existing elements and not to building up a new section of the document like this on the fly every time. At the very least, can someone point me to a good tutorial on how to accomplish what I’m trying to do here?
This is actually fairly simple to achieve and I would recommend taking advantage of some jQuery functions when writing your html building.
First
$("<tr></tr")will create a tr element stored in a jQuery object as if you had just selected it. If you are building html as above I would recommend changing to something like this in your success function.Above you will notice that You now have the attribute td generated as a jQuery object that you can apply click functions to.