There is an HTML table that needs to be updated using ajax:

<table id="types_table" border="1"> <tr> <td><h5>Ship type:</h5></td> <td><h5>Count left:</h5></td> </tr> <tr id="types_row" data-type="1"> <td>1</td> <td id="count_td">4</td> </tr> <tr id="types_row" data-type="2"> <td>2</td> <td id="count_td">3</td> </tr> <tr id="types_row" data-type="3"> <td>3</td> <td id="count_td">2</td> </tr> <tr id="types_row" data-type="4"> <td>4</td> <td id="count_td">1</td> </tr> </table> 

JS piece looks like this:

 var types = data.types_key; console.log(types); //json объект в порядке полном. for (var key in types) { console.log("type: "+key+" count: "+$(" tr#types_row[data-type=" + key + "] td#count_td").text()); } 

From the server comes a perfectly normal json object {1=4,2=3,3=2,4=1}; But I can’t apply this object to the table. selectors allocate unknown what.

 type: 1 count: 4 type: 2 count: type: 3 count: type: 4 count: 

this is what the console wrote to me. Why did the selector work for only one element? The table after all has these attributes.

    1 answer 1

    The jQuery selector on element ID returns the first element encountered. Accordingly, you have the first <tr> , and then it is filtered by the data-type .

    In order for your code to work, it is necessary for all <tr> to set the types_row class and use it in the selector, then the code will work as you want.

    • I want to clarify: should the ID in the html document be unique? - arg
    • It should be good, but if it is not unique, nothing very critical will happen. All browsers known to me normally display pages. - Vartlok
    • one
      ID MUST be unique! see w3.org/TR/html401/struct/global.html#h-7.5.2 : id = name [CS] This attribute assigns a name to an element. This name must be unique in a document., Otherwise you will always be in js with this bug toil - SanŚ́́́́́́́́́́́́́