Display record counter in dynamic text field

I have a dynamic text box that allows the user to add / remove. Firstly, the field will display records from the database.

$count = 1;
foreach($parts as $part)
{               
    echo "<input type=\"hidden\" class=\"countNumber\" value=\"".$count."\">";
    echo $count++;
}

And this is my jQuery dynamic text box.
JSFIDDLE : DEMO

I need to increase my number as soon as the user clicked +. For example, if my database consists of 5 records, then the account will be 1,2,3,4,5, and then, as soon as the user clicks the button to add a dynamic text field, the number will be continued from the previous account, and it will become 6,7,8.... Again, if the user pressed the button -, the counter will be reordered again.

But I do not know how to do this. Any help / guidance would be highly appreciated

+4
source share
3 answers

you can use classes and redefine the index using the recalculation function on click .remove. this will change the input order of input identifiers, starting from 1 time (so if you have 1,2,3,4,5 and you delete 3, all fields will be reordered as 1,2,3,4, and the next time you press +, you will add 5.)

demo: https://jsfiddle.net/p8hu7qnh/23/

function reorder() {
    var reCount = 1;
    $('.field').each(function() {
        elem = $(this);
        elem.attr('id', 'field' + reCount);
        elem.find('.number').text(reCount);
        elem.find('.hiddenField').attr('id', 'hiddenField_' + reCount);
        elem.find('.partNumber').attr('id', 'partNumber_' + reCount);
        elem.find('.description').attr('id', 'description_' + reCount);
        elem.find('.price').attr('id', 'price_' + reCount);            
        reCount++;
    });
    count = reCount-1;
};

$(document).on('click', '.remove', function() {
    console.log('removed');
    $(this).parent().remove();
    reorder();
});

EDIT demo starting at 5: https://jsfiddle.net/p8hu7qnh/25/

0
source

I think you want to get the last entry number;

  • If you repeat a lot of input with class name countNumber

you can use count = $( ".countNumber" ).last().val();

  • , , :

php:

foreach($parts as $part)
{               
   $count++;
}
echo "<input type=\"hidden\" id=\"countNumber\" value=\"".$count."\">";

js:

count = $( "#countNumber" ).val();
  • php script:

php:

echo "<script>count =".$count.";</script>"

: \". ' seperator .

2: var hidden = $('<input></input>'); html. var hidden = '<input></input>';

+3

Depending on your HTML structure, you can solve this problem using CSScounter .

I used your Fiddle and updated it a bit: https://jsfiddle.net/p8hu7qnh/26/

CSS magic:

.container {
    counter-reset: records; // Define the counter
}

li,
.added-field {
    counter-increment: records; // Increment the counter value
}

li::before,
.added-field::before {
    content: counter(records); // Render the counter value
}
0
source

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


All Articles