How to increase id on input fields using jquery on clone

I am trying to increase the form field identifier so that they are different when I click on the plus to create a new line of input fields.

Here is my code so far

//Order Form
    $("#add").click(function() {
        $('#ordertable tbody>tr:last').clone(true).insertAfter('#ordertable tbody>tr:last');
        $('#ordertable tbody>tr:last #prodcode').val('');
        $('#ordertable tbody>tr:last #meterage').val('');
        $('td.imgsample:last a').remove();
        return false;
    });

In the first line inside the click function, how can I change the input fields (prodcode and meterage) to prodcode1 meterage1 etc

+3
source share
2 answers

Assuming that you will do it more often, and then once.

//Somewhere global
var counter = 0;
//Order Form
$("#add").click(function() {
    counter++;
    var cln = $('#ordertable tbody>tr:last').clone(true);
    cln.find("[id^='prodcode'], [id^='meterage']").each(function(i, val) {
        val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
    });
    cln.insertAfter('#ordertable tbody>tr:last');
    $('#ordertable tbody>tr:last #prodcode').val('');
    $('#ordertable tbody>tr:last #meterage').val('');
    $('td.imgsample:last a').remove();
    return false;
});

Of course, there are “cleaner” solutions without using a global counter.

For the problem mentioned in the first comment, something along the lines

$("tr [id^='prodcode'], tr [id^='meterage']").live("blur", function() {
    ....
    $(this).val() //instead of $("#prodcode").val()
    ....
});

should do

+3
source
$('#ordertable tbody>tr:last #prodcode')
.val('')
.attr(
  'id', function(i,id) {
         match = id.match(/\d+?$/);
         if ( match.length ) { match++; return 'prodcode' + match } // could be match[0], may return array!
         else return id + 1 // or '2' if you wish
        }
);

for the next item.

0
source

Source: https://habr.com/ru/post/1775625/


All Articles