Click here to Skip to main content
15,902,114 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Everyone,

Scenario: Has a HTML table on a webpage already, the rows and cells in the HTML table on the page are generated from an XML file. So the whole table is created dynamically.

XML
<xsl:for-each select="xxxx">
<td align="center"  önclick="TableClicked(event)">
<span> 10 </span>
</td>
</xsl:for-each>


To Implement: I want to introduce a custom property or attribute known as "Selection" to each and every individual cell of the table.

step 1) On the OnClick events of these cells, i want to toggle this selection property to true and false (at the same time to change the background color of the cell which i am aware of how to do), so from the user side, it would be just like he made a selection of that cell (selecting and unselecting each time he clicks on it).

step 2) Any easy way to grab all the cells in the table whose selection property is true in one call, instead of going through each and every cell and seeing which ones are having the selection property true.

How would i achieve this?
Posted
Updated 14-Jun-18 22:52pm

Okay, a couple of points that come to mind.
First, the easiest way to get a list of all selected cells, is to differentiate by className instead of a custom attribute.

I would simply give the table cells a class - say tblNorm, tblSelected.
You can then use document.getElementsByClassName to get a list of either type.

Of course, it's not that many lines to get all of the selected items if you do use a custom attribute. In that case, I suppose I'd just get a list of all of the table cells, then see if the attribute was true or false.

Something like this perhaps:
HTML
<!DOCTYPE html>
<html>
<head>
<script>
function makeTbl(max)
{
	var table, tbody, tr, td, x, y, cellIndex;
	table = document.createElement('table');
	tbody = document.createElement('tbody');
	table.appendChild(tbody);
	cellIndex = 0;
	for (y=0; y<max; y++)
	{
		tr = document.createElement('tr');
		for (x=0; x<max; x++)
		{
			td = document.createElement('td');
			td.appendChild( document.createTextNode(" ["+x+","+y+"] ") );
			td.setAttribute('cellIndex', cellIndex);						// used for the display function later on
			tr.appendChild(td);
			cellIndex++;
		}
		tbody.appendChild(tr);
	}
	return table;
}

function onCellClickClassChange()
{
	var td = this;
	if (td.className == 'tblSel')
		td.className = 'tblNorm';
	else
		td.className = 'tblSel';
}

function onCellClickAttribChange()
{
	var td = this;
	var curState = td.getAttribute('selected');
	if ((curState == undefined) || (curState == 'false'))
		curState = true;
	else
		curState = false;
	td.setAttribute('selected', curState);
}


function attachHandlerToChildrenByTag(parent, eventType, functionToAttach, tagName)
{
	var mArray = parent.getElementsByTagName(tagName);
	var i, len;
	
	len = mArray.length;
	for (i=0; i<len; i++)
	{
		mArray[i].addEventListener(eventType, functionToAttach, true);
	}
}

function ShowSelected1()
{
	var tgt = document.getElementById('tgtDiv_1');
	var selList = tgt.getElementsByClassName('tblSel');
	var i, n = selList.length;
	var str = '';
	for (i=0; i<n; i++)
	{
		if ((i+1)%6 == 0)
			str += "\n";
		str += selList[i].getAttribute('cellIndex');
		if (i != (n-1))
			str += ", ";
	}
	alert(str);
}
function ShowSelected2()
{
	var tgt = document.getElementById('tgtDiv_2');
	var tdList = tgt.getElementsByTagName('td');
	var i, a=0, n = tdList.length;
	var str = '';
	for (i=0; i<n; i++)
	{
		if (tdList[i].getAttribute('selected') == 'true')
		{
			if ((a+1)%6 == 0)
				str += "\n";

			str += tdList[i].getAttribute('cellIndex');
			str += ", ";
			a++;
		}
	}
	alert(str);
}

function myOnInit()
{
	var tgt = document.getElementById('tgtDiv_1');
	var tbl = makeTbl(5);
	attachHandlerToChildrenByTag(tbl, 'click', onCellClickClassChange, 'td');
	tgt.appendChild(tbl);

	tgt = document.getElementById('tgtDiv_2');
	tbl = makeTbl(5);
	attachHandlerToChildrenByTag(tbl, 'click', onCellClickAttribChange, 'td');
	tgt.appendChild(tbl);
}
</script>

<style>
body
{
 cursor: default;
}
.tblSel
{
	background-color: #ddd;
}
</style>

</head>

<body onload='myOnInit();'>
	<div id='tgtDiv_1'></div>
	<button id='listSelectedBtn1' onclick='ShowSelected1()'>show selected cell indices</button>
	<div id='tgtDiv_2'></div>
	<button id='listSelectedBtn2' onclick='ShowSelected2()'>show selected cell indices</button>
</body>
</html>
 
Share this answer
 
v2
Comments
amarasat 6-Sep-12 16:00pm    
enhzflep,

Thanks a lot for your soultion and time, i was able to solve my issue by using the className attribute you have described in your solution. This way i was able to pull out all the elements by using "getElementsByClassName().

Your solution has solved my issue.
You can use the JQuery data[^] method to add and retrieve any kind of data to/from any element.

But I would use a html class instead. You can use JQuery addClass[^] and removeClass[^] for that (or toggleClass[^]). You dont need to assign css to that class (but you can). And You can also grab all at once easily also with jQuery.

XML
<html>
<head>
 <script src="http://code.jquery.com/jquery-latest.js"></script>
 <style>
  TD {width: 100px; border: 1px solid red;}
  TD.selected {background: lightgreen;}
  SPAN {padding: 0 1em; background: lightgreen; margin: 0 .5em;}
 </style>
</head>
<body>
<table class="table">
    <thead>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
        </tr>
    </thead>
    <tbody id="eventsTable">
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
        <tr>
            <td>4</td>
            <td>5</td>
            <td>6</td>
        </tr>
    </tbody>
</table>
<div id="allselected"></div>

<script>
 $("td").click(function() {
   $(this).toggleClass("selected");

   $("#allselected").empty();
   $("TD.selected").each(function(i)
   {
        $("#allselected").append("<span>" + $(this).html() + "</span>")
   }
   );
 });
</script>

</html>
</body>
 
Share this answer
 
v2
Comments
amarasat 4-Sep-12 16:46pm    
Thanks a lot, for the quick reply. I am very sorry to mention, the client does not want us to use jQuery. They have security issues, so it has to be a non jQuery solution. We can use DOM implementation methods though.
Zoltán Zörgő 4-Sep-12 16:58pm    
Interesting, since jquery can do as much as javascript can do. It has no security issue I know about. Although every jquery statement can be replaced with plain old javascript, but it will be only longer, nothing more.
Arunprasath Natarajan 4-Sep-12 23:33pm    
Well said
amarasat 6-Sep-12 15:58pm    
Zoltan,

Thanks a lot for your help and time, i was able to solve my issue by using the className attribute of the tag <td>. This way i was able to pull out all the elements by using "getElementsByClassName();
For Step 2:

jQuery selector $('td[Selection|="true"]') will give all the cells with the value Selection as true
 
Share this answer
 
v2
Comments
amarasat 4-Sep-12 16:46pm    
Thanks a lot, for the quick reply. I am very sorry to mention, the client does not want us to use jQuery. They have security issues, so it has to be a non jQuery solution. We can use DOM implementation methods though.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900