How to find tr table with id that matches json key and populate another column

I am new to jQuery and Json, and I came across some problems. Appreciate it very much if anyone can help me. My problem is this:

In my JSP, I have an ajax call that will return a json object to me. I want to get the keys in my json object, find those tr in my table so that their identifier matches the keys and eventually populate another column in this particular row with the value from my json object.

Here is my jquery ajax call

$.ajax({ .... .... success:function(data) { //Data is a Json Object. The value is for example :{"A":"1","B":"2","C":"3"} for(key in data) { $("#myTable tr").find(key).find("td").eq(1).html(data[key]); // not working! } } }); 

I have the following html blocks:

 <table id = "myTable"> <tr id = "A"> <td>Descriptopn.</td> <td>...</td> // I want to set this value to be 1 </tr> <tr id = "B"> <td>Description</td> <td>...</td> // I want to set this value to be 2 </tr> <tr id = "C"> <td>Description</td> <td>...</td> // I want to set this value to be 3 </tr> </table> 

My problem is that the syntax above does not work. Is there any way to do this right? Thanks.

+4
source share
3 answers

Since you have an id (and it must be unique!), You can simply use the following: -

 $('#' + key).find('td:eq(1)').text(data[key]); 

Here is the violin

+2
source

.find() searches for each matched element for the child that matches the given selector. Since you want to search for table descendants, not row descendants, get rid of tr in the original selector. Then add the '#' sign to the key to make it a valid id selector, and the rest will work as expected.

 for(var key in data) { $("#myTable").find('#'+key).find("td").eq(1).html(data[key]); // working! } 
+3
source
 $.each(data, function(i, val){ $('#myTable tr#' + i).find('td:last').text(val); }); 
0
source

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


All Articles