I have table rows that move up and down, but my problem is that the data table rows replace the table header (first row).
I want a fixed first row so that when you click the Up arrow you do not move the row up to replace the header.
I have tried some conditional logic to check if the current row is the table's first row, but it is not working.
$(document).ready(function(){
<!--- Move: click to move rows up or down --->
$(".up,.down").click(function(){
var row = $(this).parents("tr:first");
<!-- this var does not work -->
var firstrow = $('table')[0].rows[0];
<!-- Check that is not the first row NEEDS FIXED -->
if (row != firstrow){
if ($(this).is(".up")) {
row.insertBefore(row.prev());
} else {
row.insertAfter(row.next());
}
}
});
});
<table>
<tr>
<td>Do Not Replace Me</td>
<td > </td>
</tr>
<tr>
<td>Two</td>
<td>
<a href="#" class="up">Up</a>
<a href="#" class="down">Down</a>
</td>
</tr>
<tr>
<td>Three</td>
<td>
<a href="#" class="up">Up</a>
<a href="#" class="down">Down</a>
</td>
</tr>
</table>
The table must stay as is, and I cannot change td to th or anything like that.
I am hoping there is just a way to fix those two lines of code.
This would, as I suppose you know (given your disclaimer that the html must 'stay as is...'), be much easier if you could put the header/first row into a thead
element and the remainder into a tbody
, but one way that works with the html 'as is:'
$(".up,.down").click(function() {
var row = $(this).parents("tr:first");
var firstrow = $('table tr:first');
if ($(this).is(".up") && row.prevAll().length > 1) {
row.insertBefore(row.prev());
}
else if ($(this).is(".down") && row.nextAll().length > 0) {
row.insertAfter(row.next());
}
else {
return false;
}
});
Incidentally, and as an aside, your script may have been generating errors from the comment (though I do suspect the were added for our benefit, rather than in your actual JavaScript) syntax:
<!-- comment text -->
is html syntax, and within the confines of the <script></script>
tags is invalid, to comment JavaScript use either:
// single-line comment
// which needs to have the double-slash
// preface each comment-line...
or:
/* This is a multi-line
comment, and this text
will happily remain commented-out
until you get to
one of these comment-close things, just to the right -> */
References: