Reputation: 2313
I hope this is the right area, as it is more theoretical than anything else. I am currently working on a page where a user can select one or many rows to edit by clicking a checkbox in the leftmost column and clicking an Edit
button. I haven't decided if I wanted to try programming this feature, but would it be possible to effectively hide the checkboxes and use some sort of javascript or jquery to make clicking a row in a table equivalent to checking the corresponding row's checkbox? I have just started working with javascript and jquery, and I am baffled by how powerful this can be. Please inform me if this type of functionality is possible and if so, what is a general approach to achieving this behavior?
Upvotes: 0
Views: 3420
Reputation: 9881
Here is a simple implementation of the requested functionality:
$(document).ready(function() {
$('tr').click(function(e) {
var $checkbox = $(this).find('input');
var isChecked = $checkbox.prop('checked');
if (isChecked) {
$checkbox.removeProp('checked');
}
else {
$checkbox.prop('checked', 'checked');
}
});
});
Upvotes: 0
Reputation: 1610
Doable. Here's how:
HTML
<table border=1>
<tr><td><input type="checkbox"></td><td>Something 1</td><td>Something else 1</td></tr>
<tr><td><input type="checkbox"></td><td>Something 2</td><td>Something else 2</td></tr>
<tr><td><input type="checkbox"></td><td>Something 3</td><td>Something else 3</td></tr>
<tr><td><input type="checkbox"></td><td>Something 4</td><td>Something else 4</td></tr>
</table>
jQuery
$('input[type=checkbox]').parent('td').hide(); // If JS disabled, checkboxes are still visible
$('table tr').click( function() {
var $chk = $(this).find('input[type=checkbox]');
$chk.prop('checked',!$chk.prop('checked'));
$(this).toggleClass('selected'); // To show something happened
});
CSS
tr.selected{
background-color:#ccc;
}
Upvotes: 1
Reputation: 32896
Yes this is perfectly achievable, although you might like to consider the accessibility implications in the event that somebody has JavaScript disabled in their browser.
There are a number of approaches you could take. By way of example, you could use a click
handler something like the following (untested):
$(document).on('click', '#yourtable tr', function(evt) {
$(this).toggleClass('selected');
});
This would give each tr
in your table (with id #yourtable
) the class selected
which you could then either style via CSS and/or read back via another piece of jQuery.
Within the event handler you could also perform other actions to record the selection, such as updating a hidden input field, posting straight back to the server, or checking the existing checkbox (which could optionally be hidden if you prefer).
Upvotes: 1