How can I hide a row of the table(MyTable) by an id when I check checkbox(MyCheckbox) and show th开发者_高级运维e row when the checkbox(MyCheckbox) is unchecked using Jquery?
$(":checkbox").click(function(){
var index = $("#myCheckboxes :checkbox").index($(this));
$("#myTable tr").eq(index).toggle();
});
<table id="myTable">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
<tr><td>Row 4</td></tr>
</table>
<table id="myCheckboxes">
<tr><td><input type="checkbox" /> checkbox 1</td></tr>
<tr><td><input type="checkbox" /> checkbox 2</td></tr>
<tr><td><input type="checkbox" /> checkbox 3</td></tr>
<tr><td><input type="checkbox" /> checkbox 4</td></tr>
</table>
Online example:
http://jsfiddle.net/VdqNt/3/
I would give each row a unique id that may be created from each checkbox's unique id. So if you have a set of checkboxes that all have ids like "toggle-1" then each corresponding row should have an id like "row-toggle-1". Now simple bind a click event to each checkbox and have the row be shown or hidden with a conditional check on the checkbox's checked status.
Code:
jQuery(document).ready(function($) {
// bind a click function to each input element with a class of MyCheckboxes
$('input.MyCheckboxes').click(function() {
// select the corresponding table row
var corresponding_table_row = $('#row-'+this.id)
// show or hide the row depending on the checked status
if ( $(this).attr('checked') ) {
corresponding_table_row.hide();
else {
corresponding_table_row.show();
}
});
});
Here's an example that uses attributes on the checkbox to match it to the row you want to fiddle with:
<table>
<tbody>
<tr id="row1">
<td>1-1</td>
<td>1-2</td>
</tr>
<tr id="row2">
<td>2-1</td>
<td>2-2</td>
</tr>
</tbody>
</table>
<hr />
<table>
<tbody>
<tr><td><input type="checkbox" data-row="row1">Row 1</input></td></tr>
<tr><td><input type="checkbox" data-row="row2">Row 2</input></td></tr>
</tbody>
</table>
$(document).ready(function() {
$('body').delegate('input:checkbox', 'change', function() {
$('#' + $(this).data('row')).toggle(!$(this).attr('checked'));
});
});
Working example: http://jsfiddle.net/6WCmk/2/
精彩评论