About Leros
About Leros

Reputation: 190

How to use the same function twice in different elements?

I have created a table that you can add rows to with multiple input fields, however I need two tables. and i can't get the second one to work. I checked the console and no errors and I have tried copying it and changing the identifiers however that didn't work. Any help would be appreciated. code below:

$(document).ready(function() {
$("#add_row").on("click", function() {
    // Dynamic Rows Code

    // Get max row id and set new id
    var newid = 0;
    $.each($("#tab_logic tr"), function() {
        if (parseInt($(this).data("id")) > newid) {
            newid = parseInt($(this).data("id"));
        }
    });
    newid++;

    var tr = $("<tr></tr>", {
        id: "addr"+newid,
        "data-id": newid
    });

    // loop through each td and create new elements with name of newid
    $.each($("#tab_logic tbody tr:nth(0) td"), function() {
        var cur_td = $(this);

        var children = cur_td.children();

        // add new td and element if it has a nane
        if ($(this).data("name") != undefined) {
            var td = $("<td></td>", {
                "data-name": $(cur_td).data("name")
            });

            var c =   $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
            c.attr("name", $(cur_td).data("name") + newid);
            c.appendTo($(td));
            td.appendTo($(tr));
        } else {
            var td = $("<td></td>", {
                'text': $('#tab_logic tr').length
            }).appendTo($(tr));
        }
    });

    // add delete button and td
    /*
    $("<td></td>").append(
        $("<button class='btn btn-danger glyphicon glyphicon-remove row-remove'></button>")
            .click(function() {
                $(this).closest("tr").remove();
            })
    ).appendTo($(tr));
    */

    // add the new row
    $(tr).appendTo($('#tab_logic'));

    $(tr).find("td button.row-remove").on("click", function() {
         $(this).closest("tr").remove();
    });
 });

// Sortable Code
var fixHelperModified = function(e, tr) {
    var $originals = tr.children();
    var $helper = tr.clone();

    $helper.children().each(function(index) {
        $(this).width($originals.eq(index).width())
    });

    return $helper;
};

$(".table-sortable tbody").sortable({
    helper: fixHelperModified      
}).disableSelection();

$(".table-sortable thead").disableSelection();



$("#add_row").trigger("click");
});

FIDDLE

Upvotes: 1

Views: 554

Answers (2)

charlietfl
charlietfl

Reputation: 171690

I'm not going to go through all the html and make all the adjustments but will offer guidance on how to make it work.

First... since ID's can't be repeated in page you need to switch out ID's for classes.

Next you need to start at the main container element that wraps every part of this whole module. All the selectors used need to be based on looking in from this main container so they are only specific to each module instance.

You do this by using traverses like find() and closest() quite a bit .

<div class="table-responsive">
  <table class="table tab-logic"></table>
  <a class="add-button">
</div>

As with writing a jQuery plugin, wrap all the code within an each that loops the outer module containers. This loop helps us insulate the instances

var $containers = $('.table-responsive').each(function(){
     // assign variables for instance specific components

      // cache instance of this container so we don't do numerous searches for it in DOM
     var $cont = $(this),
         //there is only one table within this container         
         $table =$cont.find('table'),
         $rows = $table.children();

         // start adding events and use our cached instance collections from above
       var  $addBtn  = $cont.find('.add-button').click(function(){
            $rows.each(....

             .....
             // we know this is the instance specific table already
             $table.append(...
         });     


});

This guideline should help you make the conversion. These patterns are very common in repeating elements and you will find yourself using them a lot.

By using this approach it would also be trivial to convert the whole thing to a plugin later on if you found a need for it

Upvotes: 1

dinesh saini
dinesh saini

Reputation: 481

make two function : one for adding row, one for deleting row

run function for 1 or 2 times depends on how many rows you want.

in deleting row you should check for minimum rows allowed in this way you'll be able to delete row index 1 also,

currently row 1 is fixed

Upvotes: 0

Related Questions