jQuery is a JavaScript library that simplifies many JavaScript tasks. DOM traversal, DOM manipulation, registering events, performing Ajax calls and animation are just a few of the built-in features that jQuery simplifies. I encourage asp.net developers to look at jQuery for implementing Web 2.0 type behaviour. Recently, I gave a talk at the Toronto Visual Basic User Group (TVBUG). If you are interested the presentation is available online here.
I have decided to share some of my jQuery code on my blog. Some of the examples will be fairly simple and some will be more complicated. Hopefully may find them useful and I encourage you to cut and paste the code snippets and use them as you see fit.
The example here shows how to hide table columns. The trick is to iterate through the table row and then through the table cells of each row. If you come across a column span then you need to account for that. Here is the snippet.
<input id="column" type="text" style="width: 20px;" maxlength="1" /> <input id="hide" type="button" value="Hide Columns" />
<input id="show" type="button" value="Show All Columns" /><br/><br/>
<table id="atable" border="1" cellpadding="7" cellspacing="0">
<tr><td colspan="2">Row 1,Cell 1</td><td>Row 1,Cell 3</td><td>Row 1,Cell 4</td><td>Row 1,Cell 5</td><td>Row 1,Cell 6</td></tr>
<tr><td>Row 2,Cell 1</td><td>Row 2,Cell 2</td><td>Row 2,Cell 3</td><td>Row 2,Cell 4</td><td>Row 2,Cell 5</td><td>Row 2,Cell 6</td></tr>
<tr><td>Row 3,Cell 1</td><td>Row 3,Cell 2</td><td colspan="4">Row 3,Cell 3</td></tr>
<tr><td>Row 4,Cell 1</td><td colspan="4">Row 4,Cell 2</td><td>Row 4,Cell 6</td></tr>
</table>
<script type="text/javascript">
$(function() {
//register click event with the hide button
$('#hide').click(function() {
//go through each row in the table
$('#atable tr').each(function() {
var numcol = 0;
//go through each cell in the table row
$('td', this).each(function() {
//if the current column is greater than the value enter then hide the cell
//i have no validation implemented foe the text box
if (numcol >= $('#column').val()) $(this).hide();
//increment column number and if the cell has colspan associated with it
//then account for that as well
numcol++;
if ($(this).attr("colspan") != null) numcol += parseInt($(this).attr("colspan")) - 1;
});
});
});
});
$(function() {
$('#show').click(function() {
$('#atable td').show();
});
});
</script>
Hide Columns Show All Columns
| Row 1,Cell 1 |
Row 1,Cell 3 |
Row 1,Cell 4 |
Row 1,Cell 5 |
Row 1,Cell 6 |
| Row 2,Cell 1 |
Row 2,Cell 2 |
Row 2,Cell 3 |
Row 2,Cell 4 |
Row 2,Cell 5 |
Row 2,Cell 6 |
| Row 3,Cell 1 |
Row 3,Cell 2 |
Row 3,Cell 3 |
| Row 4,Cell 1 |
Row 4,Cell 2 |
Row 4,Cell 6 |
Try out the demo.