RememberME RememberME - 1 month ago 6
jQuery Question

Use click on table cell in subview to populate a field in the view

I have a partial view with a grid of project data. When the user enters a client into a textbox on the main view, the partialview loads as a subview to display a table of the data for all projects for that client. Two of the columns of the table are a "select" image and the project number. If the select image cell of a row is clicked, I would like to populate a textbox on my main view with the project number for that row.

How can I do this?

Answer

You could use jQuery:

$('.selectImage').click(function() {
    // an element with class="selectImage" was clicked
    // we try to fetch the value of the project number
    var projectNumber = $(this).closest('tr').find('.projectNumber').text();
    $('#selectedProjectNumber').val(projectNumber);
});

Here's a demo.

As an alternative approach you could use HTML5 data-* attributes on the select image DOM element to store the project number. For example:

<td class="selectImage" data-project-number="123">select image</td>

and then you could fetch this project number like this:

$('.selectImage').click(function() {
    // an element with class="selectImage" was clicked
    // we try to fetch the value of the project number
    var projectNumber = $(this).data('projectNumber');
    $('#selectedProjectNumber').val(projectNumber);
});

Demo.

Comments