Using jQuery to Add Numbering to a Table

I'm trying to sequential number a table, but no matter what I do, it always displays the number "2". What am I missing here? I've even tried declaring the variable outside the loop.

        <!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>    
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=geometry"></script>
<br>
<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary">
    <input type="checkbox"> BMW 1er
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> BMW Active E
  </label>
  </label>
    <label class="btn btn-primary">
    <input type="checkbox"> BMW 1er Cabrio
  </label>
  </label>
    <label class="btn btn-primary">
    <input type="checkbox"> BMW X1
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> MINI
  </label>
    </label>
    <label class="btn btn-primary">
    <input type="checkbox"> MINI Clubman
  </label>
   <label class="btn btn-primary">
    <input type="checkbox"> MINI Coupé
  </label>
    <label class="btn btn-primary">
    <input type="checkbox"> MINI Cabrio
  </label>
</div>
<br>
</head>
<body>
<font size="1"> 
<br>
<table class="table table-condensed" border="1" id="usertable"></table>
</font>
<script src="js/bootstrap.min.js"></script>
<div class="alert alert-success">
  <a href="#" class="alert-link">Die Übersicht zu Drive-Now München lädt... Bitte einen Moment Geduld!</a>
</div>
<script type="text/javascript">
var zaehler=1;
$(document).ready(function(){
function callJSON() {
    setTimeout(function () {
        $.getJSON('./url.php', function(data) {
            $ ("#usertable").empty();
            var cars = data.rec.vehicles.vehicles;
            //cars.sort(function(el1,el2){ return el1.model == el2.model ? 0 : (el1.model < el2.model ? -1 : 1); });
            cars.sort(function(el1, el2) {
            if(el1.model== el2.model) {
            if(el1.fuelState == el2.fuelState) {
            return 0;
            } else if(el1.fuelState < el2.fuelState) {
            return -1;
            } else {
            return 1;
            }
            } else if(el1.model < el2.model) {
            return -1;
            } else {
            return 1;
            }
            });

               $.each(cars, function(key, data){
                var laenge=cars.length;
                var vint=data.vin;
                var positionA= new google.maps.LatLng(data.position.latitude, data.position.longitude);
                var posiitonB= new google.maps.LatLng(48.1351253, 11.5819806);
                var entfernung= google.maps.geometry.spherical.computeDistanceBetween (positionA, posiitonB);
                var entfernung1=(entfernung/1000);
                var entfernung2=entfernung1.toFixed(2);
                var entfernung3=entfernung2+" Km";
                console.log(entfernung2);
                console.log(positionA);
                console.log(posiitonB);
                var coopers="";
                var tanken="";
                var drive="MAN";
                var fuelfarbe="#01DF3A";
                var prozent="%";
                var kosten=" 31 Cent/Min "
                var tanksymbol="glyphicon-tint";
                var farbe="success";
                var flugbadge="";
                var mode="&dirflg=w";
                var kraftstoff="BENZIN";
                var ortbadge="glyphicon-map-marker";
                var entfernungsbadge="glyphicon-resize-horizontal";
                var krafts=" ("+data.fuelState+"%)";
                var strasse=data.address;
                var v=vint.substring(3,7);
                var pdf=vint.substring(10,17);
                var pdf1=pdf+".pdf";
                console.log(pdf);
                if(data.fuelType=="DDE"){kraftstoff="DIESEL";}
                if(v=="SX31"){coopers=" S";}
                if(v=="SW71"){coopers=" SD";}
                if(data.model=="BMW ActiveE "){tanksymbol="glyphicon-flash"; kraftstoff="STROM";}
                if(data.model=="BMW X1 "){kosten=" 34 Cent/Min ";}
                if(data.auto=="Y"){drive="AUT";}
                if((48.347910654607695 < data.position.latitude && data.position.latitude < 48.35988839686733)&&(11...

                    ...
                );
            })
        }).always(callJSON);
    }, 2000);
    }
    $(callJSON);
    });
</script>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-44913908-2', 'voltdrive.de');
  ga('send', 'pageview');

</script>
</body>
</html>

Answer №1

It is important to declare zaehler outside of the $.each statement in order to avoid resetting it to 1 with each loop iteration, resulting in a value of 2 each time. And remember to remove the quotation marks as mentioned by cpreid.

var zaehler = 1;
$.each(cars, function(key, data){
     ....
    //utilize the current value of zaehler
    zaehler++;
}

Answer №2

Zaehler was classified as a string due to being enclosed in double quotation marks

let zaehler = "1";
zaehler++;

Instead, try this

let zaehler = 1;
zaehler++;

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

Incorporate a hyperlink into a column when associating data with a div element using jQuery

After bringing data through JSON and binding it in a div, I have a requirement for dynamically generating columns with its data. Specifically, there is one column in the response named APPLICATIONNAME which requires an a tag link. The code snippet to creat ...

Attach various events according to visibility status

I have a specific jquery code that I would like to bind according to the visibility of a particular box. Depending on whether the box is visible or not, I want to call different functions. Here's the code snippet that I think should work in theory. Wh ...

Placing a group of input fields and a button based on the data-id attribute of the element

I have a form that appears when a button is clicked, and the save button saves input values into an object. Is there a more efficient way to write this function if I need to create 9 more buttons with different data-id attributes (e.g. data-id="2" and so ...

Assign a URL when setting a cookie using Ajax

I'm having trouble getting a script to set a cookie using AJAX. I suspect the issue is related to the site's location or URL. Currently, the site has not been assigned a domain and is running on my local PC at: http://localhost/my-site/index.ph ...

I attempted to apply vertical-align and color properties to the static_nav div, but they didn't have any effect. Could this be due to its placement within the header? What steps should I take to resolve this issue?

<!DOCTYPE HTML> <html lang ="en"> <meta charset = "utf-8" /> <head> <title>Sample Page</title> <link rel="stylesheet" type="text/css" href="Web_Design_01_Stylesheet.css" /> </head> <body> &l ...

There appears to be a JavaScript validation error occurring on the current page, however, you are able

For my datepicker, I want an error message to display if the user selects a date more than 5 years in the future, saying "You are ineligible for our program". The user should not be able to proceed to the next step unless this error message is ad ...

Ways to create a sequential appearance of elements through CSS animations

Can you help me achieve a wave effect for elements appearing one by one using CSS animation (jQuery)? Currently, all the elements show up at once and I want to create a wave-like motion. Any assistance would be greatly appreciated. $(window ...

Various web browsers (display: -webkit-inline-box;)

Recently, I encountered an issue with my CSS code: .tudo ul { width: 100%; margin: 0px; display: -webkit-inline-box; } Surprisingly, Mozilla Firefox does not recognize the following line: display: -webkit-inline-box; Is it possible to set d ...

Send a parameter to an Angular directive when clicked

I am working on a directive that will allow me to retrieve parameters upon clicking. I need to access the child data within the click event to determine if it has children or not. ..... html div ng-app="treeApp"> <ul> <treeparent>< ...

Is there a way to create distance between these icons?

<div id="unique-icons"> <a href="#"> <img class="github-logo1" src="GitHub-Mark-64px.png" alt="first github logo"> </a> <a href="#"> <i ...

instructions for ensuring gridview spans entire width of panel

I have a gridview that is contained within a panel. I am trying to make the gridview fill 100% of the width and height of the panel. This is what I've attempted so far: CSS .pnlGridView { position:relative; float:right; heig ...

What causes the disparity in functionality between CSS's Left 75% and Right 25% properties?

Here is my CSS code snippet: .bloodparam > .highvalue { bottom: 12px; right: 25%; } and .bloodparam > .highvalue { bottom: 12px; left: 75%; } I expected the element to be in the same position with both lines of code, but I'm noticing differe ...

The icons from Materialize CSS are not displaying properly in the Safari web browser

It has come to my attention that the icons in Materialized CSS are not displaying properly in Safari (v5.1.7). Despite conducting thorough research on this issue, I have been unable to find any documentation regarding browser compatibility with Safari. Can ...

Create a CSS skeleton screen with invisible borders that do not reflect any visible outlines

I wanted to create a skeleton screen using CSS For reference, I used the link below: https://css-tricks.com/building-skeleton-screens-css-custom-properties/ However, when implementing it in my React app, I encountered an issue. Although I can see the HTML ...

Troubleshooting Margins in Bootstrap Container

Can someone help me figure out how to set consistent margins on a container using Bootstrap spacing properties without messing up the alignment?https://i.sstatic.net/unp8d.jpg * { box-sizing: border-box; } .container { max-width: 960px; } <div ...

Exploring the Power of Django Admin and Dajax

Embarking on my journey with ajax, I ask for your understanding regarding any ignorance on my part. I am exploring the example here and attempting to integrate it into the Django Admin. My focus is on developing a custom change form for the relevant model ...

Ways to retrieve the page name where the script originates from

I have a function that is triggered from three different pages. Each page involves adding an attribute to a specific div. For instance: <div id="posts" page="home"></div> <div id="posts" page="feed"></div> <div id="posts" page= ...

Performing read and write operations on targeted CSS classes using C#

I'm currently developing a C# application that needs to manipulate CSS files. Imagine you have the following CSS code snippet: .ClassOne { color: #FFFFFF; font-weight:normal; font-size: 9pt; font-family: Tahoma; ...

Querying the children of an element using jQuery

$('.Title').children(function() { var titleValue = $('.Title').text(); console.log(titleValue); }); Wondering how to access all children with the 'title' tag and log their values individually. ...

Is it possible to gather element attributes using jQuery and store them in an array

let itemWidths = []; $('#menu').children().each(function(){ let width = $(this).width(); itemWidths.push(width); }); console.log(itemWidths); This code snippet is not functioning as expected. How can I modify it to store element properties ...