0

Im trying to have a mulitple selection of cells in a table in html

Ex : I have a 4x4 table matrix And im trying to Select multiple cells

Also is it possible to create a dragable selection box around the table in order to select them

Is this possible if so can we only use javascript and css to accomplish this or do we need other softwares also

Thanks

Anoop
  • 1
  • 1
  • 1
  • it'd be easier and cleaner if you use jquery which has good library of plugins to do the exact work you want. – Shrinath Feb 08 '11 at 06:39
  • [Here][1] I've answered traditional spreadsheet-like cell selection. [1]: http://stackoverflow.com/a/31876373/760923 – Martin Aug 07 '15 at 11:16

1 Answers1

2
$("td").click(function() {
    $(this).addClass("Selected");
});

Then just use a css class called Selected to highlight them with your style of choice.

use $(".Selected") to get all selected cells

If you insist on not using jQuery then

var addEvent = function(event, elem, f) {
    if (elem.attachEvent) {
        elem.attachEvent("on" + event, f);
    } else {
        elem.addEventListener(event, f, false);
    }
};

var addClass = function(elem, className) {
    if (elem.className.indexOf(className) == -1) {
        elem.className += " " + className;
    } else {
        elem.className = elem.className.replace(" " + className, "");    
    }
};

var addSelected = function() {
    addClass(this, "Selected");
};

var tds = document.getElementsByTagName("td");

for (var i = 0, elem = tds[i]; i < tds.length; elem = tds[++i]) {
    addEvent("click", elem, addSelected);
}

See live example

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • he is reluctant to use jquery :) he wants only javascript!! – Shrinath Feb 08 '11 at 06:38
  • @Shrinath see how not using jQuery involves writing your own DOM manipulation utility functions? – Raynos Feb 08 '11 at 06:44
  • @Raynos : LoL :D if it wasn't for jquery, plain old JS would be PITA :) – Shrinath Feb 08 '11 at 06:50
  • @Shrinath JS is fine. The problem is cross-browser compliance. If I didn't use jQuery I would have a library of similar size to jQuery written by hand and less efficient. – Raynos Feb 08 '11 at 07:02
  • Hey thank you all for your quick response , just wanted to know if i could see a working example of this it would be of gr8 help – Anoop Feb 09 '11 at 07:08
  • @Anoop fixed the code from some bugs and added a live example. (It even passes JSLint!) – Raynos Feb 09 '11 at 10:38
  • AWESOME!!! Nice work Ray... works perfect , Just wanted to know if we can also have a kinda selction box on the table which will select the cells – Anoop Feb 09 '11 at 11:57