Solved

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

Posted on 2011-02-15
18
2,456 Views
Last Modified: 2012-05-11
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
Comment
Question by:Rouchie
  • 6
  • 6
  • 5
  • +1
18 Comments
 
LVL 15

Expert Comment

by:Tomarse111
Comment Utility
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
 
LVL 25

Author Comment

by:Rouchie
Comment Utility
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
 
LVL 15

Expert Comment

by:Tomarse111
Comment Utility
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
 
LVL 25

Author Comment

by:Rouchie
Comment Utility
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
 
LVL 51

Expert Comment

by:HainKurt
Comment Utility
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
 
LVL 25

Author Comment

by:Rouchie
Comment Utility
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
 
LVL 15

Expert Comment

by:Tomarse111
Comment Utility
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
 
LVL 15

Assisted Solution

by:Tomarse111
Tomarse111 earned 62 total points
Comment Utility
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
 
LVL 51

Expert Comment

by:HainKurt
Comment Utility
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 25

Author Comment

by:Rouchie
Comment Utility
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
 
LVL 51

Expert Comment

by:HainKurt
Comment Utility
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
 
LVL 51

Assisted Solution

by:HainKurt
HainKurt earned 188 total points
Comment Utility
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
 
LVL 15

Expert Comment

by:Tomarse111
Comment Utility
Please see my last code, it already covers what you are trying to achieve ...
0
 
LVL 25

Author Comment

by:Rouchie
Comment Utility
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
 
LVL 51

Expert Comment

by:HainKurt
Comment Utility
put an alert

alert(ri)

on line 10. does it shows numbers correctly?
0
 
LVL 51

Assisted Solution

by:HainKurt
HainKurt earned 188 total points
Comment Utility
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
 
LVL 82

Accepted Solution

by:
leakim971 earned 250 total points
Comment Utility
>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
 
LVL 25

Author Closing Comment

by:Rouchie
Comment Utility
Thanks everyone.  I would have never figured this one out on my own :-)
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now