Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2962
  • Last Modified:

How to find if a particular table row is odd or even?

I have a checkbox in a table row.  I reference the row from the checkbox using this markup (as the checkbox is wrapped in spans for formatting):

$("#myCbx").parent().parent().parent().parent()

Open in new window


How can I find out whether the current table row referenced by the above markup is 'odd' or 'even' within the table's rows?
0
Rouchie
Asked:
Rouchie
  • 6
  • 6
  • 5
  • +1
4 Solutions
 
Tomarse111Commented:
That doesn't seem like a very good or efficient way to create a selector ...

Could you show more of your code please, preferably the table.

Ta
0
 
RouchieAuthor Commented:
The table is pretty cumbersome (as its a GridView generated from ASP.NET), so I'd rather not show the code unless necessary.  When you say its not an effecient way to create a selector, would you rather I used the ID value of the table row directly?  If not could you please clarify?

Thanks
0
 
Tomarse111Commented:
You could use the id of the row as the context of the selector certainly, to improve the efficiency.

As to the table row problem, is there no way of adding a class onto each row ... odd ... or ... even, alternatively. This will make it a lot easier to use jQuery's native :odd or :even selectors.
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
RouchieAuthor Commented:
Okay then here's the problem which you might know of a better way to solve.

I have the following layout:

table
    rowXYZ
         cell 
              span
                   span
                         checkbox

Open in new window


When the checkbox is clicked, I have a function that shows/hides some text next to the checkbox.  That works perfectly.  However, I'd like to expand the code to change the background color of the table row for extra effect.
The problem is that ASP.NET automatically colors the alernating table rows, so JQuery needs to know whether the row is odd/even and match the original row colour if the checkbox is de-selected.
0
 
HainKurtSr. System AnalystCommented:
here is a sample:

I am marking table's rows attributes first with o/e
then add function to checkboxes
on the click function I find the row and get the attribute...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://keith-wood.name/js/jquery.datepick.js"></script>

<script>
function markTable(table) { 
  $("tr:odd", table).attr("odd","o"); 
  $("tr:even", table).attr("odd","e"); 
};

$(document).ready(function() {
markTable($("#myTable"));
$("INPUT[type='checkbox']").click(function(){
	var row = $(this).parent().parent();
	alert($(row).attr("odd") + ' : ' + this.checked);
	});
});
</script>

<table id=myTable>
	<tr><td><input type=checkbox id=myCbx1>1</td></tr>
	<tr><td><input type=checkbox id=myCbx2>2</td></tr>
	<tr><td><input type=checkbox id=myCbx3>3</td></tr>
	<tr><td><input type=checkbox id=myCbx4>4</td></tr>
</table>

Open in new window

0
 
RouchieAuthor Commented:
Thanks HainKurt

Could you advise whether it would also be possible to do something like this...

var myRow = 	$("#myCbx").parent().parent().parent().parent()
var odds = $("tr:odd", table)
// start of semi-pseudo code as my JS skills aren't great
if(odds.indexOf(myRow) > -1){
  myRow.css('background-color', '#ffcccc');
} else {
  myRow.css('background-color', 'white');
}

Open in new window


Thanks
0
 
Tomarse111Commented:
Slight alteration to Hainkurts code:


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript">
$(function(){	
	var $table=$('#myTable')	
	$table.find('tr:odd').addClass('odd');
	$table.find('tr:even').addClass('even');	
	$table.find(".odd INPUT[type='checkbox']").click(function(){		
		$(this).closest('tr').css('backgroundColor','red')		
	});	
	$table.find(".even INPUT[type='checkbox']").click(function(){		
		$(this).closest('tr').css('backgroundColor','blue')		
	});
});
</script>

<table id="myTable">
	<tr><td><input type="checkbox" id="myCbx1">1</td></tr>
	<tr><td><input type="checkbox" id="myCbx2">2</td></tr>
	<tr><td><input type="checkbox" id="myCbx3">3</td></tr>
	<tr><td><input type="checkbox" id="myCbx4">4</td></tr>
</table>

Open in new window

0
 
Tomarse111Commented:
Again slight alteration, to flick the background color on and off when clicked or de-clicked:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript">
$(function(){	
	var $table=$('#myTable')	
	$table.find('tr:odd').addClass('odd');
	$table.find('tr:even').addClass('even');	
	$table.find(".odd INPUT[type='checkbox']").click(function(){		
		var $this=$(this)
		$this.attr('checked') ? $this.closest('tr').css('backgroundColor','red') : $this.closest('tr').css('backgroundColor','');	
	});	
	$table.find(".even INPUT[type='checkbox']").click(function(){
		var $this=$(this)
		$this.attr('checked') ? $this.closest('tr').css('backgroundColor','blue') : $this.closest('tr').css('backgroundColor','');
	});
});
</script>

<table id="myTable">
	<tr><td><input type="checkbox" id="myCbx1">1</td></tr>
	<tr><td><input type="checkbox" id="myCbx2">2</td></tr>
	<tr><td><input type="checkbox" id="myCbx3">3</td></tr>
	<tr><td><input type="checkbox" id="myCbx4">4</td></tr>
</table>

Open in new window

0
 
HainKurtSr. System AnalystCommented:
yes possible. But I could not get what are you trying to do :)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://keith-wood.name/js/jquery.datepick.js"></script>

<script>
function markTable(table) { 
  $("tr:odd", table).attr("odd","o"); 
  $("tr:even", table).attr("odd","e"); 
};

$(document).ready(function() {
//$("#myTable tr:odd").attr("odd",1);
//$("#myTable").find("tbody > tr.even").attr("odd",0);
markTable($("#myTable"));
$("INPUT[type='checkbox']").click(function(){
	var row = $(this).parent().parent();
	alert($(row).attr("odd") + ' : ' + this.checked);

	if ($(row).attr("odd")=="o")
	$(row).css("background-color","silver");
	else
	$(row).css("background-color","lime");
		
	});
});
</script>

<table id=myTable>
	<tr><td><input type=checkbox id=myCbx1>1</td></tr>
	<tr><td><input type=checkbox id=myCbx2>2</td></tr>
	<tr><td><input type=checkbox id=myCbx3>3</td></tr>
	<tr><td><input type=checkbox id=myCbx4>4</td></tr>
</table>

Open in new window

0
 
RouchieAuthor Commented:
Here's what I wrote earlier...


When the checkbox is clicked, I have a function that shows/hides some text next to the checkbox.  That works perfectly.  However, I'd like to expand the code to change the background color of the table row for extra effect.
The problem is that ASP.NET automatically colors the alernating table rows, so JQuery needs to know whether the row is odd/even and match the original row colour if the checkbox is de-selected.

I'm trying to be smart in the way that JQuery colours the rows.  I was wondering whether there was a shorter method than the ATTR way you've provided.  In my page I've got this so far...

<script type="text/javascript">
/* <![CDATA[ */
function ShowHideCheckedNotice(cbxId, lblId) {
		var cbx = '#' + cbxId;
		var lbl = '#' + lblId;
		if ($(cbx).is(':checked')) {
			$(lbl).show(200);
			$(cbx).parent().parent().parent().parent().css('background-color', '#ffcccc');
		} else {
			$(lbl).hide(200);
			var myRow = $(cbx).parent().parent().parent().parent();
			var odds = $('#myTableID tr:odd');
			if(odds.indexOf(myRow)>-1){
				myRow.css('background-color', '#eeeeee');
			} else {
				myRow.css('background-color', 'white');
			}
		}
}
/* ]]> */
</script>

Open in new window


I know that odds() contains the HTML row array because I can do a window.alert and get [Object HTMLTableRowElement] in Firefox.  However, I also get these errors which I can't seem to fix...

Warning: Unknown pseudo-class or pseudo-element 'odd'.
...and...
Error: odds.indexOf is not a function

Open in new window

0
 
HainKurtSr. System AnalystCommented:
you can use $(row).attr("odd")

if ($(row).attr("odd")=="o")
  $(row).css("background-color","yellow");
else
  $(row).css("background-color","lime");

this syntax to see if it is odd or even (of course after calling markTable function)
0
 
HainKurtSr. System AnalystCommented:
or we can simplify everything and just use this

$("INPUT[type='checkbox']").click(function(){
  var row = $(this).parent().parent();
  alert($(this).closest("tr").prevAll("tr").length + 1); // this shows index of current row...
};

without doing anything else... see code

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script>
$(document).ready(function() {
$("INPUT[type='checkbox']").click(function(){
  var row = $(this).parent().parent();
  var ri = $(this).closest("tr").prevAll("tr").length + 1;

  if (ri % 2 == 0)
	$(row).css("background-color","yellow");
  else
	$(row).css("background-color","lime");

  });
});
</script>

<table id=myTable style="border:1px solid gray">
	<tr><td><input type=checkbox id=myCbx1>Option 1</td></tr>
	<tr><td><input type=checkbox id=myCbx2>Option 2</td></tr>
	<tr><td><input type=checkbox id=myCbx3>Option 3</td></tr>
	<tr><td><input type=checkbox id=myCbx4>Option 4</td></tr>
</table>

Open in new window

0
 
Tomarse111Commented:
Please see my last code, it already covers what you are trying to achieve ...
0
 
RouchieAuthor Commented:
Okay here's what I've done.  The problem is that when unchecked, the rows always turn lime and never yellow...

function ShowHideCheckedNotice(cbxId, lblId) {
		var cbx = '#' + cbxId;
		var lbl = '#' + lblId;
		var myRow = $(cbx).closest('tr');
		if ($(cbx).is(':checked')) {
			$(lbl).show(200);
			$(myRow).css('background-color', '#ffcccc');
		} else {
			$(lbl).hide(200);
			
			var ri = $(this).closest('tr').prevAll('tr').length + 1;
			if (ri % 2 == 0) {
				$(myRow).css('background-color','yellow');
			} else {
				$(myRow).css('background-color','lime');
			}
		}
}

Open in new window

0
 
HainKurtSr. System AnalystCommented:
put an alert

alert(ri)

on line 10. does it shows numbers correctly?
0
 
HainKurtSr. System AnalystCommented:
but you should use cbx I guess

var ri = $(this).closest('tr').prevAll('tr').length + 1;

-->

var ri = $(cbx).closest('tr').prevAll('tr').length + 1;
0
 
leakim971PluritechnicianCommented:
>How to find if a particular table row is odd or even?

You may use :
var odd = ( ( $(this).parents("table").find("tr").index($(this).parents("tr")) + 1 ) % 2) > 0;

Open in new window


Test page and "details" :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script language="javascript">
	$(document).ready(function() {
		$("input[type='checkbox']", "table").click(function() {
			var myRow = $(this).parents("tr");
			var allRowsInTable = $(this).parents("table").find("tr");
			var odd = ( ( allRowsInTable.index(myRow) + 1 ) % 2) > 0;
			if(odd) alert("odd");else alert("even");
		});
	});
</script>
</head>
<body>
<table border="1">
<tr><td><input type="checkbox" /></td><td>Monday</td></tr>
<tr><td><input type="checkbox" /></td><td>Tuesday</td></tr>
<tr><td><input type="checkbox" /></td><td>Wednesday</td></tr>
<tr><td><input type="checkbox" /></td><td>Thursday</td></tr>
<tr><td><input type="checkbox" /></td><td>Friday</td></tr>
<tr><td><input type="checkbox" /></td><td>Saturday</td></tr>
<tr><td><input type="checkbox" /></td><td>Sunday</td></tr>
</table>
</body>
</html>

Open in new window

0
 
RouchieAuthor Commented:
Thanks everyone.  I would have never figured this one out on my own :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 6
  • 6
  • 5
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now