HTML and CSS Reference
In-Depth Information
row += "<td>" + $("#txtColor").val() + "</td>";
row += "<td> </td>";
row += "</tr>";
$("#tblChartData").append(row);
$("#txtName").val('');
$("#txtValue").val('');
$("#txtColor").val('');
$("#txtName").focus();
});
As you can see, the jQuery code from the Add button's
click
event handler uses the
val()
method to
retrieve values entered in the text boxes. The
append()
method is then used to dynamically add a new table
row.
n
Note
You may find entering sector colors a bit tedious. The code download for this chapter includes a JavaScript
function that automatically populates the color text box with a random hexadecimal color code upon receiving focus.
For the sake of saving space, that function isn't discussed here.
Drawing a Pie Chart
The Draw Chart button's
click
event handler is responsible for drawing a pie chart on the canvas. The
complete jQuery code for the
click
event handler is given in Listing 4-28.
Listing 4-28.
Drawing a Pie Chart
var sectorNames = Array();
var sectorValues = Array();
var sectorColors = Array();
$("#btnDraw").click(function () {
context.save();
if ($("#chkGradient").is(":checked")) {
var linearGradient = context.createLinearGradient(0, 0, canvas.width, canvas.height);
linearGradient.addColorStop(0, $("#txtGradient").val());
linearGradient.addColorStop(1, 'white');
context.fillStyle = linearGradient;
context.fillRect(0, 0, canvas.width, canvas.height);
context.restore();
}
else {
context.clearRect(0, 0, canvas.width, canvas.height);
}
context.save();
$("table tr:gt(1)").each(function (i, v) {
sectorNames[i] = $(this).children("td:eq(0)").text();
})
$("table tr:gt(1)").each(function (i, v) {
sectorValues[i] = parseInt($(this).children("td:eq(1)").text());