JasonDavis JasonDavis - 4 years ago 153
Javascript Question

Get number of columns and rows selected when a mouse hovers over a table with JavaScript

Based on an HTML table that creates the below image....

enter image description here

I need to allow a user to move there mouse over the table cells and as they go right and up/down have it add the CSS class to each cell that is in the covered space


When they select the desired columns and rows for there table and click it will then add the CSS class
to all cells in the square.

It will then also get me the number of columns and the number of rows into a variable in JavaScript.

Can anyone help me achieve this? My JSFiddle here has the HTML for the table https://jsfiddle.net/qxavaja9/

add a CSS class `cell-selected

Answer Source
var columns;
var rows;
$(function() {
  $('td').hover(function() {
    var n = $(this).index();
    var m = $(this).parent('tr').index();
    $('tr').each(function(y) {
      $(this).find('td').each(function(x) {
        if (x <= n && y <= m) {
    columns = $(this).index();
    rows = $(this).parent('tr').index();


columns and rows are what you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download