position of a tr (html <tr></tr>) in the sequence of tr’s

Asked

Viewed 1,352 times

1

I have a simple screen, where I have already been able to create elements dynamically, with the click of the button, these elements are draggable up and down, and are two different elements, one textarea and a img which are added dynamically.

exemplo

I wanted to put an index (in red in the image) on each element that was added, but this index needs to be in that exact position without changing along with the elements, what I want is to link this index to the element that is in the same line of it, you know?

 <div class="wrapper">
    <input type="button" style="margin-bottom: 10px;" id="add-row" value="Adicionar parágrafo" >   
    <input type="button" style="margin-bottom: 10px;" id="add-img" value="Adicionar imagem"    >  

    <table id="t1" class="example">

        <tr id="add-template-text">
            <td></td>
            <td>
                <img class="drag-handle" src="drag2.png" height="25" width="25" alt="click and drag to rearrange" />
            </td>
            <td>
                <!--<input id="tf1" type="text" value="I am in a table row!" /> -->
                <input type="hidden">
                <textarea class="tf" rows="2" cols="25"></textarea> 
            </td>
            <td>
                <img class="row-remover" src="remove.png" height="25" width="25" alt="Remove Row" />
            </td>
        </tr>

        <tr id="add-template-img">
            <td></td>
            <td>
                <img class="drag-handle" src="drag2.png" height="25" width="25" alt="click and drag to rearrange" />
            </td>
            <td>
                <!--<input id="tf1" type="text" value="I am in a table row!" /> -->
                <input class="tf" type="file" name="pic" accept="image/*">
            </td>
            <td>
                <img class="row-remover" src="remove.png" height="25" width="25" alt="Remove Row" />
            </td>
        </tr>  
    </table>    
</div>     





 /* 
 *  jquery.dynotable.js
 *  Created on Aug 1, 2011 3:36:39 PM by bob
 */
(function($){
    $.fn.extend({
        dynoTable: function(options) {

            var defaults = {
                removeClass: '.row-remover',
                cloneClass: '.row-cloner',
                addRowTemplateIdText: '#add-template-text',
                addRowTemplateIdImg: '#add-template-img',
                addRowButtonId: '#add-row',
                addRowButtonIdImg: '#add-img',
                lastRowRemovable: true,
                orderable: true,
                dragHandleClass: ".drag-handle",
                insertFadeSpeed: "slow",
                removeFadeSpeed: "fast",
                hideTableOnEmpty: true,
                onRowRemove: function(){},
                onRowClone: function(){},
                onRowAdd: function(){},
                onTableEmpty: function(){},
                onRowReorder: function(){}
            };     

            options = $.extend(defaults, options);

            var cloneRow = function(btn) {
                var clonedRow = $(btn).closest('tr').clone();  
                var tbod = $(btn).closest('tbody');
                insertRow(clonedRow, tbod); 
                options.onRowClone();
            }

            var insertRow = function(clonedRow, tbod) {                
                var numRows = $(tbod).children("tr").length;
                if(options.hideTableOnEmpty && numRows == 0) {
                    $(tbod).parents("table").first().show();
                }

                $(clonedRow).find('*').andSelf().filter('[id]').each( function() {
                    //change to something else so we don't have ids with the same name
                    this.id += '__c';
                });

                //finally append new row to end of table                           
                $(tbod).append( clonedRow );
                bindActions(clonedRow);
                $(tbod).children("tr:last").hide().fadeIn(options.insertFadeSpeed);
            }

            var removeRow = function(btn) {
                var tbod = $(btn).parents("tbody:first");
                var numRows = $(tbod).children("tr").length;

                if(numRows > 1 || options.lastRowRemovable === true) {
                    var trToRemove = $(btn).parents("tr:first");
                    $(trToRemove).fadeOut(options.removeFadeSpeed, function() {
                        $(trToRemove).remove();
                        options.onRowRemove();
                        if(numRows == 1) {                            
                            if(options.hideTableOnEmpty) {
                                $(tbod).parents('table').first().hide();
                            }
                            options.onTableEmpty();
                        }
                    });
                }                            
            }

            var bindClick = function(elem, fn) {
                $(elem).click(fn);                
            }                  

            var bindCloneLink = function(lnk) {
                bindClick(lnk, function(){                                
                    var btn = $(this);
                    cloneRow(btn); 
                    return false;
                });
            }

            var bindRemoveLink = function(lnk) {
                bindClick(lnk, function(){ 
                    var btn = $(this);
                    removeRow(btn);
                    return false;
                });
            }

            var bindActions = function(obj) {              
                obj.find(options.removeClass).each(function() {
                    bindRemoveLink($(this));
                });

                obj.find(options.cloneClass).each(function() {
                    bindCloneLink($(this));
                });
            }

            return this.each(function() {                             
                //Sanity check to make sure we are dealing with a single case
                if(this.nodeName.toLowerCase() == 'table') {                                
                    var table = $(this);
                    var tbody = $(table).children("tbody").first();

                    if(options.orderable && jQuery().sortable) {                        
                        $(tbody).sortable({
                            handle : options.dragHandleClass,
                            helper:  function(e, ui) {
                                ui.children().each(function() {
                                    $(this).width($(this).width());
                                });
                                return ui;
                            },
                           // items: "tr",
                            update : function (event, ui) {
                                options.onRowReorder();
                            }
                        });
                    }                                 

                    $(table).find(options.addRowTemplateIdText).each(function(){
                        $(this).removeAttr("id");
                        var tmpl = $(this);
                        tmpl.remove();                        
                        bindClick($(options.addRowButtonId), function(){ 
                            var newTr = tmpl.clone();
                            insertRow(newTr, tbody);
                            options.onRowAdd();
                            return false;
                        });
                        //var contador = 0;
                        $('#add-row').on('click', function(){
                          // contador++; // somar +1
                           $('tr:last td:first-child').html($("#t1 tr").length);
                        });
                    });              

                    $(table).find(options.addRowTemplateIdImg).each(function(){
                        $(this).removeAttr("id");
                        var tmpl = $(this);
                        tmpl.remove();                                
                        bindClick($(options.addRowButtonIdImg), function(){ 
                            var newTr = tmpl.clone();
                            insertRow(newTr, tbody);
                            options.onRowAdd();
                            return false;
                        });
                       // var contador = 0;
                        $('#add-img').on('click', function(){
                            //contador++; // somar +1
                            //var contador = $("#t1 tr").length ;
                           $('tr:last td:first-child').html($("#t1 tr").length);
                        });
                    });                                
                    bindActions(table);

                    var numRows = $(tbody).children("tr").length;
                    if(options.hideTableOnEmpty && numRows == 0) {
                        $(table).hide();
                    }
                }                 
            });
        }
    });
})(jQuery);     

Here is the link with what I’ve done so far.

1 answer

3


To add a numbering in each row using jQuery, you can do something like this:

$('#t1 tbody tr').each(function(index) {
    $(this).find('td:first').text(index + 1);
});

The first row will select all rows in the table body, excluding headers, if any, through the selector #t1 tbody tr.

Then iterate over the lines using the function each, which becomes the function callback the element number.

So for each element, or line in this case, the stretch find('td:first') finds the first cell and then places the text with the line position plus one, since vectors start with zero in Javascript.

You will need to execute this code at the beginning of the table and after moving a row or any event that causes a reordering.

  • 1

    worked out! thanks! put in the time to insert, delete and reorder lines!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.