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

SizeChooser-hover
.

When they select the desired columns and rows for there table and click it will then add the CSS class
SizeChooser-selected
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();
    $('td').removeClass('SizeChooser-hover');
    $('tr').each(function(y) {
      $(this).find('td').each(function(x) {
        if (x <= n && y <= m) {
          $(this).addClass('SizeChooser-hover');
        }
      })
    })
  }).click(function(){
    columns = $(this).index();
    rows = $(this).parent('tr').index();
    $('td').removeClass('SizeChooser-selected');
    $('td.SizeChooser-hover').addClass('SizeChooser-selected');
  });
});

https://jsfiddle.net/qxavaja9/15/

columns and rows are what you want.

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