How to automatically generate a serial number using JavaScript each time a click event occurs

continuous problem with repeated serial numbers Serial number remains the same after each click

$(document).on('click', '.menu-item', function() {
    var menu_id = $(this).attr('id');
    var _token = $('input[name="_token"]').val();
    console.log(menu_id);
    var i = 1;
    $.ajax({
        url: '{{ url("waiter/menu/find") }}',
        method: 'POST',
        data: {menu_id:menu_id, _token:_token},
        dataType:"json",
        success: function(data) {
            $('#selectedMenu').append('<tr><td>' + i++  +'</td><td>' + data.name  + '</td><td><input type="number" name="quantity[]"></td><td>' + data.price + '</td><td><span class="btn btn-xs btn-danger"><i class="cancel fa fa-times"></i></span></td></tr>');
        }
    });
});

[How to update i++ for table serial number after each click]

Answer №1

Each time the var i is clicked, it will be reset to 1, so make sure to initialize it outside of the click method.

By the way, this is not the proper approach. Instead:

  1. Send the data to the server
  2. Insert a new row
  3. Calculate the total number of rows
  4. Send this count back to the client
  5. Display it as the Serial Number

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to dynamically swap out an image within an element?

Is there a way to dynamically replace this image without deleting the HTML SVG element and re-rendering it? xlink:href="http://missosology.info/forum/download/file.php?avatar=11666_1307312313.jpg" CODE: https://jsfiddle.net/bfv17f0e/ <svg class="clip ...

Unveiling the Magic: Enhancing Raphaeljs with Interactive Click Events on a Delicious Slice of the

I'm having trouble responding to a click event on each slice of a Raphael Pie Chart. I've tried implementing the code below, but it doesn't seem to be working. The code is just two lines, commented as "My Code", in the example from the offic ...

Guide to finding and saving email addresses from a string output: extracting and storing each one individually in a text file

After collecting data from multiple sources, the output I obtained is as follows: "addressId":"132234","businessEntryCount":2026},{"district":"Nordend-West","districtSlug":"frankfurt-am-main- ...

How can I make a website enable text selection?

After purchasing access to a language learning website, I was disappointed to discover that I couldn't even select text on the pages. It appears they offer an "upgrade" option for users to download lesson texts, and it seems like the ability to selec ...

If the session is not set, direct to the login page after an Ajax request

In order to ensure that the $_SESSION is set on each page, I have included a 'check session' page. This means that the 'check session' script is also included on pages with AJAX/php functionality. For example: <?php require_once gl ...

Transform the Data into JSON format

I need assistance converting my data into the correct JSON format. The current structure of my data is as follows: [ "{ id:001, name:akhilesh, }", "{ id:002, name:Ram, }" ] My goal is to transform the above data into valid J ...

Updating a multitude of values efficiently

When updating multiple fields using ajax, I retrieve a row from the database on my server, JSON encode the row, and send it as the xmlhttp.responseText. The format of the response text is as follows: {"JobCardNum":5063,"IssueTo":"MachineShop","Priority": ...

Extracting multiple values using the .find method in JQUERY / JavaScript

I'm facing an issue with my JSP page form. When I submit the form, it generates a JSON string which is sent via AJAX post. The problem arises when I try to extract multiple values from the form using the following method: .find('input[name=ite ...

What is the reason for the || operator failing to function properly in JavaScript?

In my Node.js and Express pagination setup, I encountered an issue where if the slug <= 0, it would not default to 1. new(req, res, next) { let perPage = 16; //let page = req.params.page <= 0 ? 1: req.params.page; //This works ...

Solution for Spring Ajax: Handling a Null Response with @ResponseBody

My spring webapp includes an ajax servlet that provides JSON responses using Jackson: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln ...

Aligning hyperlink with full-height image within a table cell (navigation buttons)

I am currently working on creating a traditional navigation bar that occupies 20% of the screen width and consists of 3 buttons. Each button is supposed to have an icon that is centered both vertically and horizontally. Additionally, I want the buttons to ...

How can information be seamlessly transferred between two HTML pages using a script?

For my listview, I need to pass values like "name", "info", "hap", "lat," and "lon" to page2.html. What is the best way to achieve this? In PHP, I typically use POST or GET methods, but is there a more efficient approach? If using GET is recommended, how ...

I rely on $.ajax to send data using the GET method, but for some reason I am unable to trigger the success callback function even though I successfully receive the data

Feel free to click the body details in order to view the screenshot link. Here is the code screenshot showing an issue where, when using 'post' to send data, Java is unable to retrieve the data as it appears to be 'null' ...

What is the best way to import a JavaScript class into the main.js file of a Vue.js project and make it accessible in all components without needing to import it individually in each component

I have developed JS classes that I want to import into the app.js or main.js file of my vue.js project, so that I can create instances of them in various components. Currently, I find myself having to import the same JS class separately in all components w ...

Determine the overall sum following the modification of rows

Need assistance with calculating the Grand Total of all rows to display at the bottom of a table using JQuery 1.9. Below is the JavaScript code: <script language="javascript"> $(".add_to_total").on('change', function() { var total = 0; $( ...

Is the ngShow directive dependent on the parent variable in any way?

There is a piece of code running in the $rootScope to establish a global value for userLoggedIn: mod.run(function($rootScope) { $rootScope.userLoggedIn = false; $rootScope.$on('loggedIn', function(event, args) { $rootScope.userL ...

How can you delete using JavaScript by pressing the "Delete" key?

Is it possible to programmatically trigger the deletion of text on an HTML web page using JavaScript or jQuery? I am looking for a way to replicate the functionality of clicking the "Delete" button without requiring users to physically click on it. Inste ...

Testing a function in Jest that utilizes the current date

I have a function that checks if the parameter date is the same as or later than today. In my function, I am using new Date() like this: import moment from "moment"; const validateDate = ({ date }) => { return moment(date, "DD-MM-YYYY").isSameOrAfte ...

Having trouble importing the "@angular/material" module

I'm completely new to working with the MEAN stack and currently running into issues with Angular's material module. I am attempting to bring in the "@angular/material" module into my code, but encountering an error each time I try to import it. T ...

Does jQuery provide a counter function to ajaxComplete?

I'm curious if there exists a jQuery function that acts as the counterpart to ajaxComplete? I am looking for something that can be triggered before the ajax event, similar to beforeSend $( document ).ajaxComplete(function( event, xhr, settings ) { ...