Using a simple table and jquery, how would you manually handle selection on a simple table/grid using jquery?
Here's what I've tried. You could check it out or provide your own way of selection. If there's something better or something you know that works, you don't have to read mine. I'd be happy to learn how others are doing it.
So far, I've managed to add a gridrowselected class on the tr when the click event is called so that I'll know which row is currently selected. But I don't know how to pass the selected data back to the controller (or at least an index I placed on the row).
Using a grid like this
<table id="ProjectList" class="grid reduced-full-span-grid grid-header">
<thead>
<tr>
<th class="long-col">
Title
</th>
<th class="medium-col">
Type
</th>
<th class="medium-col">
Priority
</th>
</tr>
</thead>
<tbody>
<% for ( int i = 0; i < Model.Projects.Count; ++i )
{ %>
<tr class="gridrow">
<td>
<%= Html.HiddenFor( model => model.Projects[i].ProjectId ) %>
<%= Html.TextBoxFor( model => model.Projects[i].Title,
new { @readonly = "readonly" } )%>
</td>
<td>
<%= Html.TextBoxFor( model => model.Projects[i].ProjectType,
new { @readonly = "readonly" } )%>
</td>
<td>
<%= Html.TextBoxFor( model => model.Projects[i].Priority,
new { @readonly = "readonly" } )%>
</td>
</tr>
<% } %>
</tbody>
</table>
and selection logic like this
$(function() {
$('.gridrow').click(function() {
$(this).siblings('.gridrow').removeClass('gridrow-selected');
if ($(this).hasClass('gridrow-selected') == true) {
$(this).removeClass('gridrow-selected');
} else {
$(this).addClass('gridrow-selected');
}
$(this).change();
});
});
I tried something like this
$(function() {
$('#ProjectList .gridrow').click(function() {
// Get row's index
var projectId = $(this).find('input[name$=ProjectId]').val();
// Remove the input if it already exists
var parentForm = $(this).parents('form');
parentForm.remove('input[name="selectedRows"]');
// If it is selected, create the form. If it's not selected then the input just gets removed (the user must have clicked on it and deselected the row)
if ($(this).hasClass('gridrow-selected') === true) {
parentForm.append($('<input>', { type: "hidden", name: "selectedRows", value: projectId }));
}
});
});
which I'm expecting to create a hidden input so that when I post, selectedRows gets passed onto the controller. But all it does is create the input, but the data still doesn't get passed to the controller.