How do I change the values ​​of the cloned content fields?

  • 0
    I needed to quickly clone a table row containing form fields. Naturally, these fields have name and value. How do I change name to something like name + 1 and value to value + 1. And also to perform a complete recount of the elements so that the numbering of the elements is not violated. This is because each new element can also be cloned to insert the line where it needs to be.

    So far I have taken the following code as a basis:
    function add(){
     $("table").append($("table")
     .find("#gonnaclone").clone().removeAttr("id")
     .find(".input").val($(".input").val() + 1).end());
    }
    
    var count_id = 0
    function cloneRow() {
           count_id++;
           var row = document.getElementById("gonnaclone"); 
           var table = document.getElementById("table_texts");  
    
           var clone = row.cloneNode(true); // copy children too
           clone.id = "gonna_"+count_id; // change id or other attributes/contents
           table.appendChild(clone); // add new row to end of table
    }
    JavaScript Anonymous, Dec 5, 2019

  • 1 Answers
  • 0
    in name and value - number:

    function cloneAndAdd(){
    var t = $('#table_texts');
    var cloneLastRow = t.find('tr:last').clone();
    cloneLastRow.find('[name],[value]').each(function(){
    var n = ~~this.name || 0;
    var v = ~~this.value || 0;
    this.name = ++n;
    this.value = ++v;
    });
    cloneLastRow.attr('id', 'gonna_'+(t.find('tr').length+1) );
    t.append(cloneLastRow);
    }


    in name and value - string:

    function cloneAndAdd(){
    var t = $('#table_texts');
    var cloneLastRow = t.find('tr:last').clone();
    cloneLastRow.find('[name],[value]').each(function(){
    this.value += '1';
    this.name += '1';
    });
    cloneLastRow.attr('id', 'gonna_'+(t.find('tr').length+1) );
    t.append(cloneLastRow);
    }
    Nolan Huynh

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!