views:

1421

answers:

1

I am trying to setup a function to allow moving 'up' and 'down' of a table row in a form. The number of table rows is dynamic -- the user can hit a button to add additional rows. There are multiple fields in each table row. There is a header row and footer row with different class names, hence the check of hasClassName.

I first wrote this function successfully for use with Prototype 1.6 before realizing I need for it to work with version 1.5.1. We will be upgrading to the latest version of Prototype when time is available for testing, but I need this to work under the our project's current version.

The main problem is that in 1.5 you can't just insert an Element as the content of an insertion. This means I need the HTML of the Element I want to insert. This brings up the issue that when I access the HTML for the element (variable "insertHTML") this is the original HTML and does not include the info entered into the related form elements by the user.

Any help would be greatly appreciated.

moveDataDef: function(num, dir) {
    var targRow = $('dataDefItem'+num);
    var content = targRow.innerHTML;
    var siblings;
    var insertHTML = targRow.inspect() + targRow.innerHTML + '</tr>';

    if(dir == 'up')
        siblings = targRow.previousSiblings();
    else
        siblings = targRow.nextSiblings();

    if (siblings[0].hasClassName('dataDefItem')) {
        targRow.remove();
        if(dir == 'up')
            new Insertion.Before(siblings[siblings.length - 1].id, targRow);
        else
            new Insertion.After(siblings[0].id, targRow);
    }
}
+1  A: 

Hi, I guess, you could use part of this code, to replace your lower if block. It use native DOM function, ie insertBefore():

if (siblings[0].hasClassName('dataDefItem')) {
  var targetParent = targRow.parentNode;
  var sibling = siblings[0];

  if(dir == 'up'){
    targRow.remove();
    targetParent.insertBefore(targRow, sibling);
  } else {
    sibling.remove();
    targetParent.insertBefore(sibling, targRow);
  }
}

For your reference, if you are interested, this is my POC code:

<table id="tb1">
<tbody>
<tr id="tr1"><td>1</td></tr>
<tr id="tr2"><td>2</td></tr>
<tr id="tr3"><td>3</td></tr>
</tbody>
</table>

<script type="text/javascript">
/* <![CDATA[ */
(function(){
var trr3 = $('tr3');
var tp = trr3.parentNode; 
var trr1 =trr3.previousSiblings();
trr3.remove();
tp.insertBefore(trr3, trr1[0]);
})();
/* ]]> */
</script>

Thanks.

Update: Fix typo (missing '{' and '}').

Nordin
This worked for me, though fyi ... some brackets missing in if/else statement that I had to fix. This is very similar to the Prototype 1.6 function I wrote using the Prototype's API. Will your native DOM code work cross browser?
Dan Roberts
Thanks for the correction. I believe so, it (my POC script) works on IE8 (all mode), Firefox 3, and Safari 4 beta. You may refer to Peter-Paul Koch (http://www.quirksmode.org/dom/w3c_core.html) for compatibility listing.
Nordin