Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2011-02-15
18
Medium Priority
?
2,701 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
  • 5
  • +1
18 Comments
 
LVL 15

Expert Comment

by:Tomarse111
ID: 34897205
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
ID: 34897235
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
ID: 34897292
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 25

Author Comment

by:Rouchie
ID: 34897358
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 59

Expert Comment

by:HainKurt
ID: 34897391
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
ID: 34897508
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
ID: 34897558
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 248 total points
ID: 34897600
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 59

Expert Comment

by:HainKurt
ID: 34897645
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
 
LVL 25

Author Comment

by:Rouchie
ID: 34897758
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 59

Expert Comment

by:HainKurt
ID: 34897762
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 59

Assisted Solution

by:HainKurt
HainKurt earned 752 total points
ID: 34897805
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
ID: 34897926
Please see my last code, it already covers what you are trying to achieve ...
0
 
LVL 25

Author Comment

by:Rouchie
ID: 34897929
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 59

Expert Comment

by:HainKurt
ID: 34898276
put an alert

alert(ri)

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

Assisted Solution

by:HainKurt
HainKurt earned 752 total points
ID: 34898308
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 1000 total points
ID: 34902886
>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
ID: 34905021
Thanks everyone.  I would have never figured this one out on my own :-)
0

Featured Post

Python: Series & Data Frames With Pandas

Learn the basics of Python’s pandas library of series & data frames and how we can use these tools for data manipulation.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Hi all! Recently there was EE question and the person wanted to have a multi-column textbox <div> selection, so as a first step to answer I provided a link but that was not complete with JavaScript selection, but had a good style sheet. So as a ques…
What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
The viewer will learn how to dynamically set the form action using jQuery.
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)
Suggested Courses

721 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