Home > database >  How to count from 1 when remove a row ajax?
How to count from 1 when remove a row ajax?

Time:09-16

I have to make a functionality that users can add and remove rows with input fields. Problem is that I need a row index (number) in front of each row incorrect order(1., 2., 3. etc.) also when one or more rows are removed and then added again. I can add rows but I can`t get the counting right because If I remove them then the count starts with 4 but I need 1 or if the second row gets removed then I need 2 instead of 4.

I have made it with append() and so far so good but I also need row cont in front of each row. I have a counter but let's say I add 1 row and it gives numbers 1 and 2. If I remove the second row and add another again, now the count is 1 and 3

Note that the "add" button is only one and separated from append();

I have three lines that are 1, 2, and 3, respectively

three

Now I will delete one of them. For example, I delete row number 2. I see this demo,

4,5

This should not happen. It should show the numbers 1 and 2, respectively.

<script>
    $(document).ready(function() {
        $('#educationalForm').submit(function(event){
            event.preventDefault();
            var formData = new FormData($('#educationalForm')[0]);
            $.ajax({
                url:'{{ route('educational.store') }}',
                method: 'POST',
                data: formData,
                cache:false,
                contentType: false,
                processData: false,
                success:function(data){
                    const variables = ['grade', 'major', 'end'];
                    variables.forEach(variable => {
                        if(data[variable] === null) data[variable] = '';
                    });
                    const newRowNum = $('#educationalForm tr').length   2;
                    let html = ''  
                        '<tr>' 
                        '<td class="fw-normal" id="demo">'  (newRowNum)  '</td>' 
                        '<td class="fw-normal">' data.grade '</td>' 
                        '<td class="fw-normal">' data.major '</td>' 
                        '<td class="fw-normal">' data.end '</td>' 
                        '<td>' 
                        '<form method="post" id="educational-destroy">' 
                        '@csrf' 
                        '@method('DELETE')' 
                        '<div class="btn-group">' 
                        '<a data-id="' data.id '" class="btn btn-info btn-sm" id="educationalEdit" data-bs-toggle="modal" data-bs-target="#educationalModal">ویرایش</a>' 
                        '<button data-id="' data.id '" type="button" class="btn btn-danger btn-sm" id="educationalDestroy">حذف</button>' 
                        '</div>' 
                        '</form>' 
                        '</td>' 
                        '</tr>';
                    $('#educationalTable').append(html);
                    $('#educationalForm').trigger('reset');
                },
            });
        });

        showEducationals();

        function showEducationals() {
            $.get('{{ route('educational.index') }}', function (data) {
                $('#educationalTable').html("");
                $.each(data, function (key, val) {
                    const variables = ['grade', 'major', 'end'];
                    variables.forEach(variable => {
                        if(val[variable] === null) val[variable] = '';
                    });
                    $('#educationalTable').append('<tr>' 
                        '<td class="fw-normal">'  (key 1)  '</td>' 
                        '<td class="fw-normal">' val.grade '</td>' 
                        '<td class="fw-normal">' val.major '</td>' 
                        '<td class="fw-normal">' val.end '</td>' 
                        '<td>' 
                        '<form method="post" id="educational-destroy">' 
                        '@csrf' 
                        '@method('DELETE')' 
                        '<div class="btn-group">' 
                        '<a data-id="' val.id '" class="btn btn-info btn-sm" id="educationalEdit" data-bs-toggle="modal" data-bs-target="#educationalModal">ویرایش</a>' 
                        '<button data-id="' val.id '" type="button" class="btn btn-danger btn-sm" id="educationalDestroy">حذف</button>' 
                        '</div>' 
                        '</form>' 
                        '</td>' 
                        '</tr>'
                    );
                });
            });
        }

        $(document).on('click', '#educationalEdit', function(event) {
            event.preventDefault();
            var id = $(this).data('id');
            $.ajax({
                type:'get',
                url:'/educational/' id '/edit',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success:function (data) {
                    console.log(data);
                    $('#id').val(data.educational.id);
                    $('#edit_grade').val(data.educational.grade);
                    $('#edit_major').val(data.educational.major);
                    $('#edit_avg').val(data.educational.avg);
                    $("input[name='edit_start']").val(data.educational.start);
                    $("input[name='edit_end']").val(data.educational.end);
                    $('#edit_docPlaceName').val(data.educational.docPlaceName);
                    $('#edit_thesisTitle').val(data.educational.thesisTitle);
                    $('#edit_docPlaceCountry').val(data.educational.docPlaceCountry);
                    $('#edit_docPlaceCity').val(data.educational.docPlaceCity);
                },
            });
        });

        $(document).on('click', '#educationalUpdate', function(event) {
            event.preventDefault();
            var id = $('#id').val();
            var file = $('#edit_upload_doc').prop('files')[0];
            var formData = new FormData($('#educationalFormUpdate')[0]);
            formData.append('file', file);
            $.ajax({
                type: 'POST',
                url: '/educational/' id,
                dataType: 'JSON',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (response) {
                    console.log(response);
                    $('#educationalModal').modal('hide');
                    showEducationals();
                },
            });
        });

        $(document).on('click', '#educationalDestroy', function(event) {
            event.preventDefault();
            $.ajax({
                url:'educational/' $(this).data('id'),
                type: 'DELETE',
                dataType: 'json',
                data: {
                    _token: '{{ csrf_token() }}'
                },
                success: function(response) {
                    $('#educationalsTable').html('');
                    showEducationals();
                },
                error: function(response) {
                    console.log(response);
                },
            });
        });
    });
</script>

So in general I can get counting right until elements are getting removed. If I got 3 rows I got a count of 1. 2. 3. but if I remove all of them and add again 3 rows I got 4. 5. 6. BUT I need 1. 2. 3. again

CodePudding user response:

You should reset the counter every time you re-render the whole table.

You could move the count to inside your rendering function, but it is not strictly necessary, because jQuery's each function already provides an index (you are naming it key) which you could use instead of count.

Therefore, you can do:

function showEducationals() {
    $.get('{{ route('educational.index') }}', function (data) {
        $('#educationalTable').html("");
        $.each(data, function (key, val) {
            const variables = ['grade', 'major', 'end'];
            variables.forEach(variable => {
                if(val[variable] === null) val[variable] = '';
            });
            $('#educationalTable').append('<tr>' 
                '<td class="fw-normal">'  (key 1)  '</td>'  // using key instead of count

Notice I also removed id=demo. This is because you are creating several cells with the id=demo (in '<td class="fw-normal" id="demo">' count '</td>' ) and ideally ids should be unique.

About adding new rows use, instead of i, the number of rows the table actually has:

$('#educationalForm').submit(function(event){
    event.preventDefault();
    var formData = new FormData($('#educationalForm')[0]);
    $.ajax({
        url:'{{ route('educational.store') }}',
        method: 'POST',
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        success:function(data){
            const variables = ['grade', 'major', 'end'];
            variables.forEach(variable => {
                if(data[variable] === null) data[variable] = '';
            });
            const newRowNum = $('#educationalTable tr').length   1; // added this
            let html = ''  
                '<tr>' 
                '<td class="fw-normal">'  (newRowNum)  '</td>'  // edited this

In addition, you should remove the i and count variables, as they are no longer necessary:

showEducationals();
let i;                 // remove this
let count = 1;         // remove this
function showEducationals() {
    // ...
            );
            i = count  // remove this
        });
  • Related