Posts Tagged ‘Magic: The Gathering’

Clickable Table Rows with jQuery

Wednesday, January 27th, 2010 by Phillip Napieralski

Check out the demo here!

This tutorial hints at a project I’m working on. A deck building application for the Magic: The Gathering card game.

Highlighting Rows

In jQuery Selectors 2, I talked about how to highlight certain rows in a table. We can build off this to begin a full sized app (at least the frontend) with jQuery.

To recap briefly, we allow rows be clickable by using the following code:

$(document).ready(function() {
	$("tr").click(function(){
		// store our selection of the row that was clicked
		row = $(this);

		// toggle the "selected" class for the clicked row
		row.toggleClass("selected");
	});
});

Note first that the code is inside the $(document).ready(…) function. This will be the case for the code in the rest of this post.

Show Card Selections

How do we know what the user selected? Well, we can accomplish that task with the following code:

	// check for a button click
	$("#show_button").click(function(){
		var cards = "";
		
		// search through each row that has the "selected" class
		$("tr.selected").each(function() {
			// append the card name (which is between <th> tags) to our cards variable
			cards += $(this).find("th").html();
			cards += "\n";
		});

		// Simply alert the user what they selected for now
		alert("You selected:\n"+cards);
	});

There you have it. The next step is to replace the alert(“”) piece with a $.post(…) request to a php script with the selected cards.

Next Time

Lost on this tutorial? Try part 2