Can someone please explain move up - move down table row code that is pasted

Hello, this might sound lame but I have found a code that uses JQuery framework to move table rows up and down. But I am unable to understand this code, I am a newbie with JQuery. So could someone throw some light on what this code is doing.

I am unable to understand what is "var row = $(this).parents("tr:first");", as when I try to get its ID, all it gives me is undefined??

How would I get the IDs for elements of the rows being moved?? I am unable to traverse through the table at all, what would be the method to get the innerHTML or text of cells of each row??

I need to learn this inorder make some changes to this code to make this work for me.

<html>
<head>
<script type="text/javascript" src="Demo/js/jquery-1.3.1.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
    $(".up,.down").click(function(){
      alert(this.id);
        var row = $(this).parents("tr:first");
      alert(row.cells[0].innerHTML);
        if ($(this).is(".up")) {
            row.insertBefore(row.prev());
        } else {
            row.insertAfter(row.next());
        }
    });
});
</script>
</head>
<body>
<table id='tab'>
    <tr id='t1'>
        <td>One</td>
        <td id='td1'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t2'>
        <td>Two</td>
        <td id='td2'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t3'>
        <td>Three</td>
        <td id='td3'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t4'>
        <td>Four</td>
        <td id='td4'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t5'>
        <td>Five</td>
        <td id='td5'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
</table>
</body>
</html>
gautam_reddycAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
read comments
$(document).ready(function(){
    $(".up,.down").click(function(){
	//this here refers to the link that you clicked since the links are the ones that
	//have class="up" or class="down". Since none of them have an id, then you get a blank
	//alert window.
      alert(this.id);

	//row is NOT a DOM node, so you cannot do alert(row.id); IF you do so, you will get undefined
	//row is a jQuery object that refers to the first tr.
        var row = $(this).parents("tr:first");
	   alert(row.id);//should alert undefined
	   
	   //if you want the actual DOM node you need to call .get(0) on the jQuery object
	   //row = row.get(0)
	   
	   //IMPORTANT: The above line "changed" row from a jquery object to a DOM node!
	   //so here you DO get the atual id
	   alert(row.id);//should NOT alert undefined
	   
	//and innerHTML is DOM node property so you WILL get the actual HTML
      alert(row.cells[0].innerHTML);


        if ($(this).is(".up")) {
	   	//because of the conversion from jQuery object to DOM node
		//these will fail because these are jquery methods NOT DOM methods
		//NOT a DOM method

            row.insertBefore(row.prev());
        } else {
            row.insertAfter(row.next());
        }
    });
});

Open in new window

0
hieloCommented:
more comments regarding how to actually access the cell and row id via jquery. Should "demystify" the mystery! :)

Regards,
Hielo
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
    $(".up,.down").click(function(){
      alert(this.id);
	 
        var row = $(this).parents("tr:first");
	   
	   //to get the id of the row from the jquery object use:
	   alert(row.attr('id'))
	   
	   //again, since row is NOT a DOM reference, you cannot access the cells[]
      //alert(row.cells[0].innerHTML);
	 
	  //instead you can say "access the first <TD> within row and then alert its
	  //html via the .html() method
	  alert( $("td:eq(0)", row).html() )
        if ($(this).is(".up")) {
            row.insertBefore(row.prev());
        } else {
            row.insertAfter(row.next());
        }
    });
});
</script>
</head>
<body>
<table id='tab'>
    <tr id='t1'>
        <td>One</td>
        <td id='td1'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t2'>
        <td>Two</td>
        <td id='td2'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t3'>
        <td>Three</td>
        <td id='td3'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t4'>
        <td>Four</td>
        <td id='td4'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t5'>
        <td>Five</td>
        <td id='td5'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
</table>
</body>
</html>

Open in new window

0
gautam_reddycAuthor Commented:
Thanks a lot hielo, Now I see light at the end of the tunnel.

In regular javascript, I would use the below mentioned steps to retrieve all html elements in a given row, how should I proceed with JQuery??

var row = document.getElementById(rowId);
if(row !==null && row!= null)
{
var elems = row.getElementsByTagName('*');
for(var i in elems)
{
elems[i].id;
}
}

Also could you advice me on how should I proceed with changes for both rows? Now I have to manipulate ids and names of HTML elements in both the rows.

0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

hieloCommented:
assuming you have initialized rowId somewhere:
//var row = document.getElementById(rowId);
     row=$('#'+rowId);
     
     //if(row !==null && row!= null)
     if(row.size())
     {
     	//var elems = row.getElementsByTagName('*');
     	var elems=$('*',row);
     	
     	/*
     	for(var i in elems)
     	{
     		elems[i].id;
     	}
     	*/
     	elems.each(function(i,DOMNode){
     		alert( i+": "+ DOMNode.innerHTML);
     	});
     }

>>Also could you advice me on how should I proceed with changes for both rows?
I don't know what you mean/expect, but based on what you posted:
>>elems[i].id;
You should now be able to manipulate the properties of the DOM nodes within the .each() I posted.

Open in new window

0
gautam_reddycAuthor Commented:
Yes both rows I meant were the rows which would be changed during this. On click of either up or down, two rows interchange positions, for suppose I have 3 rows, and click up on row number 3, it would go into 2nd row's place and 2nd row goes to 3rd place. So I would now have to change the row IDs and elements' IDs with their respective row indexes. I wanted your suggestion on that.

Also what is the # for in "row=$('#'+rowId);"??
0
hieloCommented:
>>Also what is the # for in "row=$('#'+rowId);"??
the assumption is that rowId has a value like "t1" since you posted:
var row = document.getElementById(rowId);

in jquery you don't do:
$("t1");

you do:
$("#t1")

save the attached code as hielo.html and try it
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
    $(".up,.down").click(function(){
       
        var row = $(this).parents("tr:first");
           
        if ($(this).is(".up")) {
            row.insertBefore(row.prev());
        } else {
            row.insertAfter(row.next());
        }
	   
	   var table=$(this).closest("table");
	   
	   //the i is the index of the row on the current table.
	   //they start at index 0 (think arrays)
	   $("tr",table).each(function(i,v){

		//within this function, the usage of 'this' refers to the current tr
		//because i starts at zero, you need to add 1
	   	$(this).attr("id","t"+(1+i));


		//now look for the cell that contains an id that begins with 'td'
		//remember that 'this' refers to the current tr, so the statement below
		//is saying "look for a td whose id starts with 'td', but limit your
		//search to 'this' row (the current row of the iteration)
	   	$("td[id^='td']",this).attr('id','td'+(1+i))
	   });

	//view final result
		alert(table.html())
		
		alert("Problem solved :) ")
    });
});
</script>

</head>
<body>
<table id='tab'>
    <tr id='t1'>
        <td>One</td>
        <td id='td1'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t2'>
        <td>Two</td>
        <td id='td2'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t3'>
        <td>Three</td>
        <td id='td3'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t4'>
        <td>Four</td>
        <td id='td4'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr id='t5'>
        <td>Five</td>
        <td id='td5'>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
</table>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gautam_reddycAuthor Commented:
Hielo when I do alert( $(this).attr("id","t"+(1+i)));, I do not get the row Ids but I get "[object Object]" this. I am not sure if I am making a mistake somewhere.  Same goes for the table data cells too when use alert to print them.
0
hieloCommented:
SET a new value:
$(this).attr("id", "New ID VALUE")

GET the value of the ID attribute
$(this).attr('id')

since you are trying to alert the new value, so you need to use only ONE parameter to attr():

alert( $(this).attr("id") )
0
gautam_reddycAuthor Commented:
Thanks a lot of JQuery 101 Hielo. Thank you for being patient and helping solve my doubts.
0
gautam_reddycAuthor Commented:
You are the MAN!!
0
hieloCommented:
Anytime little grasshopper, anytime :)

Regards,
Hielo
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.